19

Can I extract a transform's settings from its handle? I'm trying to avoid upscaling images using the workaround, and I'd like to set my transform handle dynamically within some conditionals. (see this link).

Say I'm looping through a matrix field as in the example below, using a dropdown variable to determine which transform is best. When outputting the image I'd like to replace that '970' with pixel width specific to that the asset transform. I'm sure this is wrong, but I'm imagining something like getTransform(transform).width.

{% if block.formation == 'twins' %} 
    {% set transform = 'medium' %}
{% else%}
    {% set transform = 'large' %}
{% endif %}

<figure>
  <img src="{% if image.getWidth() > 970 %}{{ image.getUrl(transform) }}{% else %}{{ image.url }}{% endif %}" alt="{{ image.title }}" />
</figure>
0

1 Answer 1

20

Sortof – you can find out what an image’s width would be with a transform applied to it via AssetFileModel’s - getWidth() and getHeigth()

<img src="
    {%- if image.getWidth(transform) > 970 -%}
        {{ image.getUrl(transform) }}
    {%- else -%}
        {{ image.url }}
    {%- endif %}" alt="{{ image.title }}" />

And for extra cleanliness points, you can update the code to use setTransform() instead of jumbling all that code into your <img> tag:

{% if image.getWidth(transform) > 970 %}
    {% do image.setTransform(transform) %}
{% endif %}

<img src="{{ image.url }}" alt="{{ image.title }}" />
2
  • 9
    Thanks Brandon! I award you a correct answer, 12 gold coins, and a stack Exchange invisibility cloak. Once you reach 7 merit badges you will be elegible for meta.meta.meta.craftcms.stackexchange.com. (currently in private beta). Commented Jun 12, 2014 at 0:26
  • 1
    That's so meta. Commented Jun 12, 2014 at 0:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.