1

I'm trying to display an image as a banner above the items of a view (which creates a block). The image is a field associated to a taxonomy term and the view is used to display all items which have this term. Is it possible to inject the image into the render array using a hook in order to access and render it on a specific location inside the view's template (for example block--views-block--example.html.twig)? I can't find a good solution anywhere on the web. I'm thinking of something like this (pseudo code):

function suitable_hook(&$vars) {
  $image = getFieldOfTaxonomyTerm('taxonomy_term', 'image_field_name');
  $vars['associated_image'] = $image;
}

If there are better approaches to this problem in general, please let me know as well. Thanks a lot in advance for your suggestions!

5

This can be done entirely from within the Drupal UI.

If you already have access to the taxonomy term in the view, you can add the term entity directly.

This is what the core taxonomy term pages view does.

To see for yourself, go to /admin/structure/views/view/taxonomy_term on a standard Drupal 8/9 installation.

In the header, you will find Global rendered entity: Taxonomy term. If you click this to open up the settings, you will see that Drupal is loading the term based on the argument {{ raw_arguments.tid }}, which is provided by the Contextual Filter Content: Has term ID. (Check the settings there as well.)

For your own block, I would use this same technique. You say you want to render the image, not necessarily the whole taxonomy term. To do that, I would create a new View Mode for the term that only has the image and whatever else you want to display.

You can create a View Mode for a taxonomy term by going to the "Manage Display" page for the relevant taxonomy vocabulary.

Then, in Views, in the header where you are rendering the term entity, you can set the view mode to your new custom view mode.

3
  • Thank you for the clear explanation. That helped a lot and probably saved me hours of work! However, I'm not seeing something like {{ raw_arguments.tid }} for my custom view and so I have to type the exact taxonomy term ID. This still works fine in this case, but where would I enable this? – Boostinger Oct 13 '20 at 17:42
  • Inside your Contextual filter settings there should be a section called Replacement patterns. That is where you can see the available tokens. – prkos Oct 13 '20 at 18:06
  • @Boostinger Depending on the structure of the view, you may need to add the taxonomy term as a Relationship. Adding a term as a relationship will make all the tokens + fields for the term accessible in the view. – Patrick Kenny Oct 13 '20 at 18:20

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.