1

I want to get the node title inside an image.html.twig override so I can use it to replace the 'title' and 'alt' attributes of the image. So far I was able to pass simple variables with THEME_preprocess_image(&$variables) but no luck getting the title of the parent node.

1

1 Answer 1

1

The cleanest solution that I could find is to get node object in image-formatter.html.twig which is a wrapper to image.html.twig.

Add THEMENAME_preprocess_image_formatter to your THEMENAME.theme

function THEMENAME_preprocess_image_formatter(&$variables) {
  $variables["node"] = $variables['item']->getEntity();
}

Copy core/themes/classy/templates/field/image-formatter.html.twig into your THEMENAME/templates directory.

Now you can get the node title in this twig file using {{node.getTitle()}} or {{node.label()}}

The twig file might look like this

Node title: {{node.getTitle()}}

{% if url %}
  <a href="{{ url }}">{{ image }}</a>
{% else %}
  {{ image }}
{% endif %}

Don't forget to rebuild cache (clear cache) for the changed hooks/twig files to be seen by your Drupal installation.

Alternatively if you want to just change the alt and title attributes of your image based on the node title here is one way to do it (covers question in the comments)

function THEMENAME_preprocess_image_formatter(&$variables) {
  $node = $variables['item']->getEntity();
  $variables["image"]["#alt"] = $node->label();
  $variables["image"]["#title"] = $node->label();
}
5
  • Thanks for the answer. Your solution worked as you said and I was able to print the title of the node inside image-formater.html.twig. The problem is that I need the title inside {{ image }} so I can replace the 'title' and 'alt' attributes and I think the corresponding template is the image.html.twig but when I tried to do that by replacing: Feb 12, 2019 at 12:09
  • THEMENAME_preprocess_image_formatter() with: THEMENAME_preprocess_image() I get Error: Call to a member function getEntity() on null Am I missing something. Is the image.html.twig the template I need or there is a way to override {{ image }} inside image-formater.html.twig? Feb 12, 2019 at 12:15
  • yes entity is not available inside THEMENAME_preprocess_image, I am not sure why. As a workaround you can bring all the code you have in image.html.twig inside image-formatter.html.twig and put it where right now there is {{ image }}.
    – GiorgosK
    Feb 12, 2019 at 12:36
  • If you implement the workaround just make sure other image fields don't break.
    – GiorgosK
    Feb 12, 2019 at 12:44
  • @NikosKakos also look at alternative solution in my answer based on your comment question.
    – GiorgosK
    Feb 12, 2019 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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