0

Is it possible to run hook_preprocess_node() only for the main page, and not for the referenced nodes that are on that same page?

I am using the following code, but it doesn't feel like the best option.

function mymodule_preprocess_node(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
  if ($current_alias === $variables['url']) {
    //run code
  }
}
1
  • 1
    hook_preprocess_node() runs for every rendered node and you don't want to stop it running in some cases because the rest of the Drupal ecosystem assumes that it runs. Instead, update your code to only execute for the correct view mode, e.g. full as @apaderno suggests. This is usually enough. It gets more complicated if you need to vary on something other than view mode because then you need to worry about modifying cache metadata.
    – sonfd
    Jun 16 at 14:44

1 Answer 1

2

If the other nodes are rendered using a different view mode, you can check that $variables['view_mode'] is 'full' or the view mode used for rending nodes on /node/[nid].

Otherwise, you can verify the node ID that appears in the URL is equal to $variables['node']->id(). You should not need to check path aliases, as Drupal should internally convert the path alias to the normal path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.