1

Is there an easier way to achieve this? Perhaps using a |filter function?

{% set variantIds = [] %}
{% for variant in product.variants %}
  {% set variantId = variant.id %}
  {% set variantIds = variantIds|merge([variant.id]) %}
{% endfor %}

{% if wheelSpacer in variantIds %}
  this spacer
{% endif %}

3

Using the |map filter would work nicely here:

{% set variantIds = product.variants|map(variant => variant.id) %}

{% if wheelSpacer in variantIds %}
    ...
{% endif %}
3

You could use filter to get only the variant that matches the wheelSpacer variable. This will return an array, so you can use first to get the first matching variant (since presumably product.variants won't contain duplicate variants). This has the added benefit of getting you the matching variant directly, instead of it's ID:

{% set variant = product.variants|filter(variant => variant.id == wheelSpacer)|first %}
{% if variant %}
    {# ... #}
{% endif %}

As a sidenote, if your variants field is an Entries field, you'll want to use product.variants.all() instead.

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.