Drupal 8 display an image_style in a Twig Template with Twig Tweak

This example is related to displaying styled images in a Drupal 8 Paragraph template for the fields of a Paragraph, but still applies to other templating sichuations where a file URI is available in the template vars.

Install the twig_tweak module (heres the module cheat sheet ) which provides this function, which will return a styled image URL from a file URI:

{{ 'public://images/ocean.jpg'|image_style('thumbnail') }}

Inside the Paragraph template html.twig file create a new variable:

{% set image = content.field_image_machine_name['#items'].entity.uri.value|image_style('image_style_machine_name') %}

You can not use the file URL which is accessible by:

{{ content.field_image_machine_name.0 }}

When configuring the Display Format of the image field there is no option to return file URI, choose the format “Url to Image” in Home > Administration > Structure > Paragraphs types > Paragraph Type Name.

Views Templates

The image URL for the styled image is easy to get in Views. Simply set the “Formatter” to “URL to image” and select the style from “Image style”, Views handles the rest.

Homework


It seems intensive digging into the documentation and source comments is the only way to start using Twig templates effectively. At this stage of learning despite reading “Discovering and Inspecting Variables in Twig Templates” I have no idea how to know that [‘#items’] has this data in it or where it’s written in documentation that this exists. I also don’t know how to work out that content.field_machine_name.0 has the file URL in it when a dump() of content and content.field_machine_name is always empty. Is the extra headache really worth it just to be more MVC patterned? The merits of Twig can be found on this Aquia Twig blog post. I will come back to this thought in a few months time.

Was this article helpful?
YesNo