2

I have a very basic macro for a lazyloading responsive image tag:

{% macro isotopeItem(imgParam) %}

  {% set thumb = { mode: 'fit', width: 100, quality: 60, } %}
  {% set tSM = { mode: 'fit', width: 1536, quality: 80, } %}
  {% set tMD = { mode: 'fit', width: 340, quality: 80, } %}
  {% set tXL = { mode: 'fit', width: 1536, quality: 80, } %}

    <img
    src="data:image/gif;base64,{# yadayada #}"
    data-sizes="auto"
    data-src="{{ imgParam.url(thumb) }}"
    alt="{{ imgParam.title }}"
    data-srcset="
      {{ imgParam.url(tSM) }} {{ imgParam.getWidth(tSM) }}w,
      {{ imgParam.url(tMD) }} {{ imgParam.getWidth(tMD) }}w,
      {{ imgParam.url(tXL) }} {{ imgParam.getWidth(tXL) }}w"
    class="lazyload" />

{% endmacro %}

As you can see the image transformations are inside the macro which is not very nice.

How do I write the transformations outside the macro and then pass it into it? I tried tried to write one param for each transformation:

{% set thumb = { mode: 'fit', width: 100, quality: 60, } %}
{% set tSM = { mode: 'fit', width: 1536, quality: 80, } %}
{% set tMD = { mode: 'fit', width: 340, quality: 80, } %}
{% set tXL = { mode: 'fit', width: 1536, quality: 80, } %}

{% macro isotopeItem(imgParam, transformParam1, transformParam2 {# and so on #}) %}
   {# responive image srcset code like the above example #}
{% endmacro %}

{# I then would have to call the macro like this: #}

{{ _self.isotopeItem(asset, thumb, tSM, tMD, tXL) }}

This works but I have to pass all the transforms everytime I use the macro.

There must be a better way right?

3

Edit: I changed it to your variables, not sure if I set the array brackets 100% correct but the idea should work.

You could set the defaults in the macro as you already did, then in your template call the macro and pass the options e.g. :

{% set image = block.slide.first() %}
{# macro #}
  {% set imgParam = [
    thumb: { quality: 60, },
    tSM: { mode: 'crop', width: 1536 },
%}

{% macro isotopeItem(imgParam) %}

and merge the passed options in the macro with your macros defaults e.g.:

 {% set defaults = [
    thumb: { mode: 'fit', width: 100, quality: 60, },
    tSM: { mode: 'fit', width: 1536, quality: 80, },
    tMD: { mode: 'fit', width: 340, quality: 80, },
    tXL: { mode: 'fit', width: 1536, quality: 80, }
  ]
%}

{% set imgParam = imgParam ? defaults|merge(imgParam) : defaults %}

so you will only need to pass explicit changes.

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.