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.