So I have setup a macro based on the excellent article here;
https://straightupcraft.com/articles/responsive-images-with-twig-macros
{% macro responsive(asset, options={}) %}
{% import _self as self %}
{% set options = {
alt: '',
class: [],
style: 'default'
}| merge(options) %}
{% set transform = {
mode: 'crop',
} %}
{% set nativeWidth = asset.getWidth(false) %}
{% set config = {
default: {
srcsetWidths: [300, 600, 1000,],
sizes: [
'(max-width: 47.5em) 100vw',
'50vw'
],
defaultWidth: 600
},
cards: {
srcsetWidths: [345, 600, 700, 905, 1000, 1200, 1400],
sizes: [
'(max-width: 47.5em) 100vw',
'(max-width: 60em) 50vw',
'33vw'
],
defaultWidth: 600
}
} %}
{% set params = config[options.style] %}
{% set srcset = [asset.getUrl(false)~' '~nativeWidth~'w'] %}
{% for width in params['srcsetWidths'] %}
{% if width < nativeWidth %}
{% set srcset
= srcset|merge([asset.getUrl(transform|merge({width: width}))~' '~width~'w'])
%}
{% endif %}
{% endfor %}
<img
{# src attr: transformed only if necessary #}
{% if nativeWidth <= params['defaultWidth'] %}
src="{{ asset.getUrl(false) }}"
{% else %}
src="{{ asset.getUrl(transform|merge({width: params['defaultWidth']})) }}"
{% endif %}
srcset="{{ srcset|join(', ') }}"
sizes="{{ params['sizes']|join(', ') }}"
alt="{{options.alt}}"
{{ self._classAttr(options.class) }}
/>
{% endmacro %}
However, I want to be able to generate each individual responsive set based on different transform parameters. The first instance I have is created a series of card images images for a 1x3 row of feature cards. These will be a fixed ratio which I want the system to handle and not the user. These cards have the following sizes for each srcset width;
- 1400 x 875
- 1200 x 750
- 1000 x 625
- 905 x 566
- 700 x 438
- 600 x 375
- 345 x 216
I have created an image transform in the Control Panel called Card Image that has been set to crop and the width/height set to the largest size (1400x875). I wondered if I could use this handle in the macro, but I run into errors;
The merge filter only works with arrays or "Traversable", got "string" as first argument.
As I will have different use cases and create different 'responsive images' throughout the site, I want the flexibility of setting up different transforms, I thought it was perhaps sensible to keep these all in the control panel under the Image Transforms section, as these are easily referable and editable. Then pass in the required handle into the Macro.
Does anyone have a better approach or solution, and any ideas how I can overcome the error mentioned?
Thanks.