Motivation
Context between template variable arrays is an old problem already known in D6 and 7 on theming level. What about D8 now? Any light on the horizon? Any chance to make this avaible without using Views module tweaks and work arounds?
Let's use an example:
Default standart content type Article has 4 input fields:
- label (title)
- body (main text area)
- image
- tags (terms, entity reference)
This content type also has an alternative Manage Fields Display setting for the Teaser view mode, where the image field formatter is set up using a smaller Image Style and with the option to link to the file or full node page. This creates an <a>
element with url but without title or any other attributes around the Article image markup in Teaser view mode.
The question:
How can I hand over e.g. the first value of the tags (input terms) programmatically to a classes array of the wrapping <a>
element?
In node--view--frontpage.html.twig
this ...
`<a href="#" class="image icon fa-{{ (content.field_tags['0']['#title']) }}">{{ content.field_image }}</a>`
... works. Sure, because we grab it from the page variable. But image-formatter.html.twig
is deeper nested inside the whole template system and it would be an overload to have the whole page variable array available here. Of course it is not there.
My assumption was to use the following preprocess functions:
function theme_preprocess_field(&$variables) {}
and orfunction theme_preprocess_image_formatter(&$variables) {}
The problem:
It seems - even if _preprocess_image_formatter
has been suggested in the twig comments of the image-formatter.html.twig
- there is 1.) no place to pass a string to any kind of attributes array for the <a>
element in this twig file since the array has no given place for that. 2.) The hand over. How? Global vars are mostly not the best solution.
The core template code of image-formatter.html.twig
:
{% if url %}
<a href="{{ url }}">{{ image }}</a>
{% else %}
{{ image }}
{% endif %}
The drafted alternation to demonstrate the needed effect:
{% if url %}
<a href="{{ url }}"{{ some defined attributes }}>{{ image }}</a>
{% else %}
{{ image }}
{% endif %}
NOTE: adding values manually and directly in the twig theme file like
<a href="{{ url }}" class="hallo-classes">{{ image }}</a>`
shows that this is the right twig template. But it seems there is no way to get other values handed over (here), since _preprocess_image_formatter
$variables array doesn't know any values of other fields of course (like of tags term field). And _preprocess_field()
doesn't reach the image formatter level so that an addition to the attributes array rather affects the surrounding div but not the <a>
element.