4

I call a asset like this:

{% set headImage = entry.geschaeftsbereichHeadImage.first() %}
<img src="{{ headImage.url(headBanner) }}"

If I don't ad any image to this field there is a twig error:

Impossible to invoke a method ("url") on a null variable

When I don't ad any Image to this field in the CP shouldn't there be just no image? Why the error? If I ad a image it works just fine.

6

Well, the first method only tries to get an asset model. But if there's no asset added to the field it simply returns null. So calling a method like getUrl, or accessing a property like url or title can't work, as they do not exist for null.

{% set image = entry.geschaeftsbereichHeadImage.first() %}

{% if image %}
    <img src="{{ image.url(headBanner) }}">
{% endif %}

Or if you'd like to display a fallback image consider somthing like this:

{% set image = entry.geschaeftsbereichHeadImage.first() %}
{% set imageUrl = image ? image.url(headBanner) : 'path/to/fallback.jpg' %}

<img src="{{ imageUrl }}">

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.