geerlingguy / jeffgeerling-com

Drupal Codebase for JeffGeerling.com
https://www.jeffgeerling.com
GNU General Public License v2.0
38 stars 2 forks source link

Decouple About page library from node ID to its title #136

Open bmartinez287 opened 2 years ago

bmartinez287 commented 2 years ago
 // Add resume assets on 'About' page.
  if ($node->id() == '1') {
    $variables['#attached']['library'][] = 'jeffgeerling/resume';
  }

Replaced it with

 // Add resume assets on 'About' page.
  if ($node->getTitle() == "About") {
    $variables['#attached']['library'][] = 'jeffgeerling/resume';
  }

Alternative ways to get a node title
$node->label()
$node->getTitle()

https://api.drupal.org/api/drupal/core%21modules%21node%21src%21Entity%21Node.php/function/Node%3A%3AgetTitle/9.3

geerlingguy commented 2 years ago

This would make for a more flexible setup, though one difficulty with the approach (for one individual site) is that the title field is not universally unique, therefore it's possible other nodes could be called "About" and get the changes :D

But for my site, I know I don't have any other nodes with "About" and that wouldn't be so bad.

I do wonder performance-wise, if comparison with int vs string would make much of a difference (if the site is being hammered with hundreds of requests per second).

bmartinez287 commented 2 years ago

Yeah, I was thinking about doing something like this to overcome the challenge that could come with multiple pages titled about.

// Add resume assets on 'About' page.
  if ($node->getTitle() == "About" && $node->toUrl()->toString() == "/about" ) {
    $variables['#attached']['library'][] = 'jeffgeerling/resume';
  }

However, that is more verbose. In regards to performance, I'm not sure. I suppose a string would be more based on memory allocation. However, if node 1 ever gets deleted which is unlikely but if it could happen then it would require a PR.

There are a few other items that I might open an issue for but feel free to let me know if you rather keep them as they are. I probably keep it as an issue until the issue gets approved if it gets approved. Once It's been green-lighted, I will work on a PR for it.

Resources https://drupal.stackexchange.com/questions/272522/how-to-get-nid-and-title-from-a-node-array https://drupal.stackexchange.com/questions/230746/get-path-alias-from-nid-or-node-object https://www.php.net/manual/en/language.types.intro.php