3
votes

I want to enhance the title of a page with a taxonomy term value that has been set in a field.

So the title looks like this:

Title - [taxonomy-term-value]

To modify the title, i overwrote

field--node--title--[content-type].html.twig

So far so good, access to the node itself and the other fields are requested through the element object:

element['#object'].get('field_my_field').get(0)

To get the first element.

element['#object'].get('field_my_field').get(0)['target_id']

returns the tid of the taxonomy term. But

element['#object'].get('field_my_field').get(0)['name']

returns an empty element.

How can the field value be retrieved? I cannot imagine that this should require php code.

Update: I figured out a way, but it seems a bit complicated:

Since the taxonomy terms are not resolved in #object, i had to add a hook_preprocess:field function to prepare a variable with the necessary data:

function myTheme_preprocess_field(&$variables, $hook){
  if ($variables['field_name'] == 'title'){
    $variables['my_field'] = Term::load($variables['element']['#object']->get('my_field')->get(0)->getValue()['target_id']);
}

The field can now be accessed in twig as follows:

{{ my_field.name.getValue()[0]['value'] }}

To me this seems to be like a lot of work, so a more straight forward approach is much appreciated.

4

4 Answers

2
votes

This should work!

{{ my_field.name.value }}

EDIT:

The way you access the name of a term (or any field) changes depending on the template your code is in.

If you are in a paragraph template you would use:

{{ paragraph.field_my_taxonomy.name.value }}

If you are in the node template:

{{ node.field_my_taxonomy.name.value }}
2
votes

In Drupal 8, if you only have the TID of the term, the contrib module Twig Tweak should let you get the Term name by doing :

{{ drupal_field('name', 'taxonomy_term', tid) }}
0
votes

To me, looks like you need to set up a proper page_suffix for the page-title.html.twig template, populated by your custom module

0
votes

What worked for me in a node template was:

{{ node.field_name.entity.name.value }}