1

I've set up four custom image transforms on the page and would like the content editor to be able to select which size they want the image to be from a drodown field preconfigured with the transformation names. This is all within a Matrix field, btw. This answer was close, and helped me put .value on the end of my dropdown field variable, but it must only work with pre configured image transforms in Craft's settings.

Here is the code (simplified):

{# medium 16:9 #}
{% set landscapeMd = {
  width: 439,
  height: 247,
  quality: 80,
} %}

{# medium 9:16 #}
{% set portraitMd = {
  width: 278,
  height: 494,
  quality: 80,
} %}

{% for block in entry.productCollage %}
  {% switch block.type %}
    {% case "digitalProduct" %}
      // selected via dropdown field
      {% set transformType = block.imageAspectRatio.value %}

      <figure>
        {% for image in block.image %}
          <a href=""><img src="{{ image.url(transformType) }}" alt=""></a>
        {% endfor %}
      </figure>
  {% endswitch %}
{% endfor %}

What I get with this code is an error that says the selected image transform is not available. However, if I type in that image transform verbatim, it works fine.

1

landscapeMd and portraitMd are variables... they would need to be strings (or array keys) for this to work.

Try something like this:

{# medium 16:9 #}
{% set landscapeMd = {
  width: 439,
  height: 247,
  quality: 80,
} %}

{# medium 9:16 #}
{% set portraitMd = {
  width: 278,
  height: 494,
  quality: 80,
} %}

{% set transforms = {
  'landscapeMd': landscapeMd,
  'portraitMd': portraitMd
} %}

{% for block in entry.productCollage %}
  {% switch block.type %}
    {% case "digitalProduct" %}
      // selected via dropdown field
      {% set transformType = transforms[block.imageAspectRatio.value] %}

      <figure>
        {% for image in block.image %}
          <a href=""><img src="{{ image.url(transformType) }}" alt=""></a>
        {% endfor %}
      </figure>
  {% endswitch %}
{% endfor %}

This maps the transforms with the transforms object, then references the key in transforms[block.imageAspectRatio.value].

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.