Allowing Editors to Choose the Image Style in Drupal 8 Image Fields
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:
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'.
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.