12

I have a series of variables I want to make available on twig templates for specific content templates.

In MYTHEME.theme I have:

function MYTHEME_preprocess_node(&$variables) {

  if (isset($variables['node'])) {

    $mycustomblock = \Drupal::service('plugin.manager.block')
      ->createInstance('myblock', []);

    $variables['mycustomblock'] = $mycustomblock->build();

    $headertext = \Drupal::service('plugin.manager.block')
      ->createInstance('headertext',
        [
          'text-align-submit'  => 'right',
          'uppercase-submit'   => TRUE,
          'header_size'        => 'h4',
          'header-size-submit' => 'h4',
          'grid-size-submit'   => 6,
          'header-title'       => 'This is a test',
        ]
      );

    $variables['headertext'] = $headertext->build();
  }
}

This allows me to use {{ headertext }} and {{ mycustomblock }} in content type templates like node--contenttype1.html.twig and node--contenttype2.html.twig. But I'd rather not build the 'headertext' and 'mycustomblock' variables for every single node type when I only need each one for one content type. It'd be nice to have a switch or if statement that checks which content type it is before generating a variable with a block.

Is there a way that I can check the content type of the node?

I've tried

$type = $variables['node']->type;

But that did not work.

15

To get the content type of a node, you just use $variables['node']->getType() or $variables['node']->bundle(). The first method just calls the second, so calling one or the other one doesn't make much difference.

public function getType() {
  return $this->bundle();
}

The only difference is that bundle() is defined for every entity, since the concept of bundle is common for all the entities, while content type is the property Drupal used for nodes before changing them in one of the entities Drupal core modules implement; using bundle() makes easier to adapt the code for other entity types, but I don't think it is the case for the code you are using.

5

You have to use $variables['node']->getType(). Also if you need it on some view modes only, consider doing a check on this as well, with $variables['view_mode']

2

You can add the node (and view type) to your hook function name:

function MYTHEME/MYMODULE_preprocess_node__nodetype__display(&$variables) {
  // ...
}

For example, for the page node type in full mode:

function MYTHEME/MYMODULE_preprocess_node__page__full(&$variables) {
  // ...
}

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.