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>
nicael
  • 2,382
  • 7
  • 27
  • 48
James Muspratt
  • 423
  • 2
  • 10

1 Answers1

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 }}" />
Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137
  • 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). – James Muspratt Jun 12 '14 at 00:26
  • 1
    That's so meta. – Jeremy Gimbel Jun 12 '14 at 00:40