I have copied the field.html.twig Template to field--node--field-image--article.html.twig, to specialize the template for my needs. In this case the template would be called for content type article and field type image. (This content type uses the Responsive Image module.)

As default, with the image field, you must define an alt-value for the image. But the alt-value is processed in the template image.html.twig.

Is it possible, to access the alt-value in the field--node--field-image--article.html.twig (the copy of field.html.twig), which calls the image.html.twig via the responsive-image templates.

I want to display the alt text in a div near the image.

I also have tried to access it in hook_preprocess_field(), but all I have for now is the following code.

function mytheme_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#field_name'] == 'field_image') {
    foreach ($variables['element']['#items'] as $item_key => $item) {
      // code to write

With twig a preprocess function won't be necessary to get at this data (yay). Unfortunately we still have some weird "drupalisms" to deal with due to the render API. At any rate, here's how you get to it:

{{ item.content['#item'].alt }}

And here's the issue on d.o accounting for the drupalism (linked directly to comment with the above solution and explanation): https://www.drupal.org/node/2160611#comment-9358305

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.