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