I'm keen to set my image variants dynamically from content editor and not quite sure how I do this in twig.

I have three variants. They are named imageVariantsThumb, imageVariants16by9, and imageVariants3by2 in craft.

To render the variant on the image I use the following.

{% set optimizedImages = item.itemImage.one().imageVariantsThumb %}

Depending on the dropdown selected in the editor (say the values are thumb, 16by9 and 3by2) I want to change the variant name in this line of code. How do I use the value from my drop-down field to change the variant name on the end of the code above?

I have tried defining a variable using the value and replacing imageVariantsThumb above but it doesn't work:

{% if block.listImageRatio == '16by9' %}
  {% set imageRatio = 'imageVariants16by9' %}
{% endif %}

{% set optimizedImages = item.itemImage.one().imageRatio %}

So instead of using the dot syntax ., this would be a good place to use the subscript syntax [].

{# dot syntax #}
{{ foo.bar }}

{# subscript syntax #}
{{ foo['bar'] }}

When you use the subscript syntax to access a variable's attributes, you can safely use variables (by just removing the single quotes surrounding the attribute).

{% set bar = 'helloWorld' %}
{{ foo[bar] }}
{# functions just like foo.helloWorld #}

So for your example, you would do this:

{% if block.listImageRatio == '16by9' %}
    {% set imageRatio = 'imageVariants16by9' %}
{% endif %}

{% set optimizedImages = item.itemImage.one()[imageRatio] %}

(Twig docs)

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.