2

is there a way to render a value from a node of custom content type in html.html.twig?

E.g. in my custom content type "book" I have a field called "author_name". I now like to render the node value of "author_name" anywhere in html.html.twig.

Is this somehow possible using just twig? I tried a few things with extends, embed, include etc, but nothing worked so far.

1
  • Content type itself has no values. I suppose you mean a value from a particular node of a custom content type. Please clarify your question.
    – ya.teck
    Nov 24 '16 at 16:47
3

Load the node and get the field value in a preprocess hook:

function mytheme_preprocess_html(&$variables) {
  if ($variables['node_type'] == 'book' && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $variables['node_field1'] = $node->field_field1->value;
  }
}

This makes sense to check first for the correct content type, because then you know which fields are defined. Otherwise you would have to check if the field is present to prevent an error. But then you have already loaded the node for nothing.

Output the value in twig:

{{ node_field1 }}
1
  • Thx, that works. I was thinking of making use of the Twig extends function, e.g. inside the node template extending the header which is inside html.html.twig. But that didn't work. This would be very useful e.g. to create meta tags or microdata related to a node type.
    – benandunt
    Nov 28 '16 at 18:51

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.