Impossible to invoke a method on a null variable I call a asset like this:

{% set headImage = entry.geschaeftsbereichHeadImage.first() %}
&lt;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.
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 %}
    &lt;img src="{{ image.url(headBanner) }}"&gt;
{% 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' %}

&lt;img src="{{ imageUrl }}"&gt;