I have two product types. One has variants. One has not.

So I try to write an image tag that works for both.

{% set imageThumb = item.defaultVariant.variantThumb.one()  %}

For the product with one variant this returns:

Impossible to invoke a method ("one") on a null variable.

This works only for the product type with multiple variants. defaultVariant doesn't seem to be present on products with just one variant.

Trying to fit both cases with one and with multiple variants:

{% for item in craft.products.all() %}
   {% if item.defaultVariant | length %}
     {% set imageThumb = item.defaultVariant.variantThumb.one()  %}
   {% else %}
      {% set imageThumb = item.variantThumb.one()  %}
   {% endif %}
      <img src="{{ imageThumb.url }}"
 {% endfor %}

This code is not working. How do I have to write this?


The problem is that item.defaultVariant will always be true even for products without visible variants (see docs on that), so you can't test for it.

You don't really need to test for it though - just look first for images held against the product, and fallback to images held against the default variant like this:

{% for item in craft.products.all() %}
    {% set imageThumb = item.variantThumb|length ? item.variantThumb.one() :
        item.defaultVariant.variantThumb|length ? item.defaultVariant.variantThumb.one() 
    <img src="{{ imageThumb.url }}">
{% endfor %}

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.