Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using preprocess hook on specific node type in Drupal 8

I've had success using preprocess page hooks such as:

function mytheme_preprocess_page__node_front(&$variables) {
    ...
}

and

function mytheme_preprocess_page__node_12(&$variables) {
    ...
}

which correlate with custom templates named page--front.html.twig and page--12.html.twig, respectively.

I'm trying to implement the same hook and template pairing for a content type called Video. I understand that there is a difference in that my examples have been custom templates for specific pages while my goal is a custom template for an entire content type, but I got a custom template called node--video.html.twig that works as a template for all video pages. However when I try to write a hook based on this template name:

function mytheme_preprocess_node__video(&$variables) {
    ...
}

this does not work. I think that I either can't define a hook like this, or I'm just naming it incorrectly. I found a couple threads somewhat relating to this such as this that seem to imply that I need to define a hook for all nodes and then write an if statement that handles each type separately. So.......

Final Question: Can I define a hook for an entire content type, and if so what am I doing wrong?

like image 343
ConorBaumgart Avatar asked May 03 '17 23:05

ConorBaumgart


People also ask

How to get node type in Drupal 8?

In order to get current content type: $node = \Drupal::routeMatch()->getParameter('node'); $typeName = $node->bundle(); $typeLabel = $node->getTitle();

What is hook preprocess?

function hook_preprocess This hook allows modules to preprocess theme variables for theme templates. It is called for all theme hooks implemented as templates, but not for theme hooks implemented as functions.

What is preprocess function in Drupal 8?

Preprocess functions allow Drupal themes to manipulate the variables that are used in Twig template files by using PHP functions to preprocess data before it is exposed to each template. All of the dynamic content available to theme developers within a Twig template file is exposed through a preprocess function.


1 Answers

Use condition within the preprocessor to get the node type and then either do your logic within, or invoke another function.

function mytheme_preprocess_node(&$variables) {
  switch ($variables['node']->getType()) {
    case "video":
      // ...
    break;
    case "something_else":
      // ...
    break;
  }
}

You could in theory emulate what you are trying to achieve by trying to invoke a function named mytheme_preprocess_node__" . $variables['node']->getType() if it exists, but is too much fuss without a clear benefit.

like image 92
bbujisic Avatar answered Dec 28 '22 23:12

bbujisic