Let's say I have a channel called testimonial which has a field called customerImage.

I want to use a twig template to display information about the customer, which may or may not have an image set.

So, inside the twig template for the channel, I have:

<div class="whatever">
    {% include '/_includes/showImage' with {
        image: testimonial.customerImage
    } %}

The question is, do I need to check for testimonial.customerImage being set before passing it to the include, if the include already checks it?

The showImage.twig file uses it as follows:

{% if image and image.one() %}

Is this correct or do I have to check if it exists before using it even to pass the value?

1 Answer 1


My assessment would be if testimonial will never be null and customerImage will always exist (note: not the same as having an asset attached), you can do that if your logic within the include template checks for the existence of an actual image on the field and then calling .one() to get the asset, before outputting anything image related.

The way you have done it is probably the way I'd do it, as you are then having your include do the logic check so it's organised. Equally doing it the way you have done it also allows you to provide an alternative layout to fallback to without an image if you wanted.

  • Thanks. My main concern is if something would result in a fatal error when an image is not set and I use the value to pass it. But from your answer I assume this is not a problem! ;) Commented Jul 4, 2022 at 21:44
  • @AlvaroFranz In this case, both the section and field itself will exist on the entry for the include to be valid, you are then doing your checks for an actual asset image to then use, so no the include shouldn't cause any issues. Commented Jul 4, 2022 at 21:51
  • Thanks. Im accepting this answer because it answers the original question. Curiosity: in what case would the field not exist and throw an error? Only if it is not defined in Craft? I mean, always, when the field exists in Craft, will nit exist in the template as "null" when defined but not used? Commented Jul 4, 2022 at 21:53
  • 1
    Generally yes, if the field exists in your fields table and it's on the content table (unless a matrix field), it can't not exist but if the field isn't on your entry type template, it will likely have no value i.e. null. You just have to bear in mind with Twig when calling objects on variables in a chain, if there's a chance that one can be null, you need to either use null coalesce or check before trying to use it, but in this case, your section is unlikely to never not exist and the image field is a defined field in Craft, but defensive coding is still something to be aware of. Commented Jul 4, 2022 at 22:02

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.