Craft Commerce newbie question....

How do I display the image asset for a custom variant field?

I'd like to display the associated image of a product variant in the cart.

1 Answer 1


Ok so in general this depends on if the custom field is on the product or the variant. Assume the filed is called masterImage either way.

If the field is on a variant: {% set image = lineItem.purchasable.product.masterImage.first() %}

If the field is on the product: {% set image = lineItem.purchasable.masterImage.first() %}

Remember (either way) you should always check there is an image first really:

{% if lineItem.purchasable.product.masterImage|length %} ... set the image

In practise I usually have code that falls back to the product image if the variant image is not set for whatever reason:

    {% set image = lineItem.purchasable.masterImage.first() ?? null %}
    {# Fallback on product image if there is no variant image set #}
    {% if not image|length %}
        {% set image = lineItem.purchasable.product.masterImage.first() ?? null %}
    {% endif %}

(Note here I am not doing the initial test on the asset because I am instead using the null coalescing operator)

  • Okay, so I have tried displaying the field on the variant with:
    – JackO
    Oct 14, 2016 at 8:29
  • But an error returns with Variable "lineItem" does not exist
    – JackO
    Oct 14, 2016 at 8:31
  • Yep you will need to loop through the line items ... Check the Commerce docs on order models...I'm in a taxi ;) Oct 14, 2016 at 8:42
  • I'm currently doing so with {% for item in cart.lineItems %}
    – JackO
    Oct 14, 2016 at 9:04
  • Change it to for lineItem in... Oct 14, 2016 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.