Category Technology
Publication date
29 March 2017

Allowing Editors to Choose the Image Style in Drupal 8 Image Fields

Time to read 2 minutes read

While building a site recently, we had a requirement for teaser images to be in a landscape or portrait orientation. We could have created two image fields and told the client to just fill in one - but that would mean editors would be responsible for cropping the image which would add extra effort to their work. Instead what we did was used one image field and one select list to choose if they image should be 'landscape' or 'portrait' in teasers.

Hang on, doesn't that mean that the age old problem of people's heads getting chopped off will rear it ugly head (excuse the pun)? In the olden days, yes; but given the AMAZING work the Drupal Media team has done, we were able to use a cropping tool (Image Widget Crop) to allow editors to choose how each image would look for each image style created. This means one image uploaded to the site, reused in many representations, without fault. How we did that can be explained in another blog post - for now, these screenshots should suffice to show how seamless our solution works:

Drupal 8 media crop - landscapeDrupal 8 media crop - portrait

And now for our solution to allow editors to choose which version of the image they wanted for teasers. What we did was created another text field with two options 'Landscape' and 'Portrait'.

Drupal 8 node edit form teaser section

Then in the twig file for the teaser view mode (node--teaser.html.twig) we checked what the value of this field was. We then used the 'Twig Tweaks' module to load the image with the corresponding image style.

The code looks like this:

This blog post was inspired by Third & Grove's blog post - One Image Field, Multiple Aspect Ratios.

Profile picture for user Mark Conroy

Mark Conroy Director of Development

When not promoting sustainable front-end practices at conferences across Europe, Mark leads our development team to create ambitious digital experiences for clients, so they, in turn, can have success with their clients.