0

I have added a header image field to most of my entities of my website so that the header image can be overwritten if needed. On any node, my code in my page.html.twig file works perfectly:

{% if node.field_header_image.entity.uri.value %}
  <section class="hero d-flex" style="background-image: url({{ file_url(node.field_header_image.entity.uri.value) }})">
{% else %}
  <section class="hero d-flex">
{% endif %}

However, I've added a field_header_image field to my taxonomy terms and can't seem to find a way to get the code I need to print on my page.html.twig file.

On my taxonomy page template file, if I print the following code: {{ file_url(elements['#taxonomy_term'].field_header_image.entity.uri.value) }} I get what I need but this doesn't work in page.html.twig file.

Any suggestions on how I can access this? Or is there another way for me to overwrite the header image on my taxonomy terms?

EDIT: Is there a way to do this through a preprocess?

  • I know this might not help much now you've done all this work but was there a specific reason for doing this in a tpl? A much better solution might have been to make a block using views or custom code and then just place that in whatever block region you need (or even add a new region if needed). So it takes the logic or retrieving data and doing if statements out of the template which is the prefered route – Leigh Mar 2 '18 at 15:36
  • It was the way that was suggested by a consultant so we just went about it that way. The title of the page is displayed above these background images so that was the route we went. It's worked fine for everything except the taxonomy pages. – ACanadianCoder Mar 2 '18 at 15:47
  • Probably because the page has no context of taxonomy term? IMO this is best solved with a View and a block output to a region. – Kevin Mar 2 '18 at 16:19

Browse other questions tagged or ask your own question.