How do I load an image from a taxonomy custom field into a custom location on the taxonomy page template?

It's easy to accomplish it when the image is in a node. The following code works for images, but it doesn't work for taxonomy pages.

    {{ file_url(node.field_reference_background.entity.uri.value) }}

How can I accomplish the same for taxonomy pages?


Only entities from type node are loaded in the page template by default. If you want this for other entity types you have to add custom code to page preprocess:

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['term'] = $term;

Then you can access the fields from the term in page--taxonomy.html.twig:

{{ file_url(term.field_image.entity.uri.value) }}
  • You are the man! That is exactly what I was looking for! Many thanks!!! ++ Feb 18 '17 at 18:06
  • is there a way to also exclude the newly declared field from further output on the page? I see that if you remove it from the display it will not show further but I wonder if theres a way I can do that purely with the theme? Feb 18 '17 at 22:48
  • If you want to exclude the field in twig, then put {{ content|without('field_name') }} in taxonomy-term.html.twig.
    – 4k4
    Feb 19 '17 at 9:00
  • Supplementary answer / another option, if you are instead using the taxonomy term twig, e.g. taxonomy-term.html.twig - I found this to work: <img src="{{ file_url(term.field_image.entity.field_media_image.0.entity.uri.value) }}"/> where field_image is the field "image" added to the taxonomy term entity of type Media (an entity reference) and field_media_image is the field of the Media entity that the field_image refers to. Apr 25 at 20:29

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.