jeffgeerling-com icon indicating copy to clipboard operation
jeffgeerling-com copied to clipboard

Decouple About page library from node ID to its title

Open bmartinez287 opened this issue 4 years ago • 2 comments

 // 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

bmartinez287 avatar Oct 24 '21 19:10 bmartinez287

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).

geerlingguy avatar Oct 24 '21 22:10 geerlingguy

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

bmartinez287 avatar Oct 25 '21 00:10 bmartinez287