简体   繁体   中英

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?

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 }}

The only way i founded was to preprocess the node of the page to get the content of the taxonomy field.

Here a example of my code

$node = \Drupal::routeMatch()->getParameter('node');
    $field = 'title';
    $index = 0;
    if($node){
        $nodeArray = $node->toArray();
        if (isset($nodeArray[$field][$index]['value'])) {
            $value = $nodeArray[$field][$index]['value'];
        }
        if(isset($nodeArray['field_home_page_slider_type'])){
            $id_slider_type = $nodeArray['field_home_page_slider_type'][0]['target_id'];
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM