I have added the field "Product Image" to my products. The field is an "asset field" which enables me to upload an image for each product. The field handle is productImage.

How can I output this image in my template?


Welcome to Craft!

A very basic piece of code for displaying your image would look like this (the if statement first checks if the field actually has an asset or not):

{% if product.productImage|length %}
    <img src="{{ product.productImage.first.getUrl() }}" />
{% endif %}

This quite simply outputs the image as it has been added in Craft, full size. Of course this isn't ideal as the images could be huge. That's why we have Image Transforms, which allow you define the size of the images.

Here is the above code again, but updated to use a new transform we have created in Craft called 'Test Transform', with a handle of 'testTransform':

{% if product.productImage|length %}
    <img src="{{ product.productImage.first.getUrl('testTransform') }}" />
{% endif %}

Hopefully that gets you started. I'd recommend reading through the Craft docs for using and templating asset fields.

  • 1
    I'd advise adding a if product.productImage.first()|length around those examples. Otherwise if there is no image set on the product you'll get an exception raised. May 26 '16 at 22:37
  • @JeremyDaalder Good point, I've updated the answer.
    – Jamie Wade
    May 27 '16 at 8:36

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.