3

Using Drupal 8.

I want to display the value of a field (field_date) at the top of my page, in the header, so I need to output it in page.html.twig. I'm having issue with this, though, which I think boil down to the scope of where variables are available.

To clarify - I can print field_date in node.html.twig no problem by just using content, but since I need it so high on the page, I'm hoping for a way to print it in page.html.twig.

I'm open to any solution, but here's a possible solution I picked up from searching on this same topic:

In THEMENAME.theme

/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
    $element = $variables['element'];

    if($element['#field_name'] == 'field_date') {
        $variables['promo_date'] = $element[0]['#markup'];
        dpm($variables['promo_date']);
    } 
}

In page.html.twig:

<div class="theme-date">{{ promo_date }}</div>

In this example, the dpm does work, but the promo_date displays nothing. Doing kint(node) returns a large number of methods, but none seem to be the fields I need. Unfortunately the solution I borrowed from was taking a page-level variable and adding it to field.twig.html, and I think the scope reversal is the problem.

3

If you want to see the result of your code in THEMENAME_preprocess_field() you have to put {{ promo_date }} in a field.html.twig.

But in your question you asked about the page.html.twig. To access the field value in this template, you can use the node object, which is preloaded in the page template. But only if there is a node in the url of your page. Otherwise this will return an empty string:

{{ node.field_date.value }}
  • Does this mean I cannot use cleaner URLs, such as /page-name ? – GFeesh Feb 14 '16 at 16:58
  • That doesn't matter, the url can be an alias of the node too. But if you display a view, where nodes are inside, this will not work. – 4k4 Feb 14 '16 at 17:30
  • Okay, thank you. This is exactly what I needed. Previous attempts at using node I got bogged down in the structure/finding the value, but I gave up too soon. – GFeesh Feb 14 '16 at 23:08

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.