phpdrupaltwigdrupal-8drupal-taxonomy

Drupal 8 get taxonomy value in twig


I'm working on Drupal 8,
I have a content type, called Home page, with fields of content and one field of type Entity Reference who is linked to a taxonomy item.
In page.html.twig I want to get the value of this taxonomy item.

I tried a lot of think but nothing works.

a read than I need to do this code:

{{node.field_home_page_slider_type}}

but it give me a white page. I tried with kint, I'have a lot of property but I dont found how to get the value of my field.

What's the solution?


Solution

  • If you are still struggling with twig, just prepare what you need in your_theme.theme. You can get your node in

    function HOOK_preprocess_page(&$variables) {
      if (!array_key_exists('node', $variables))
        return;
      $node = $variables['node'];
      // ...
    

    }

    Here you can prepare your data and provide it for twig like this:

    $variables['foo'] = 'bar';
    

    In Twig you can do this:

    {{ foo }}