2

I've a problem with this code. I get the error message:

Impossible to invoke a method ("getUrl") on a null variable.

For this code:

{% if siteBgBlureFallback %}
    background-image: url({{ siteBgBlure.first().getUrl('bodyBg') }});
{% endif %}

Here is the full code:

{% if entry is defined %}
    {% set siteBg = entry.siteBg %}
    {% set siteBgBlure = entry.siteBgBlure %}
{% endif %}

{% set siteBgFallback = siteBgFallback.siteBg %}
{% set siteBgBlureFallback = siteBgFallback.siteBgBlure %}

.bg {
{% if siteBg is defined and siteBg is not empty %}
    {% if siteBg %}
        background-image: url({{ siteBg.first().getUrl('bodyBg') }});
    {% endif %}

{% else %}

    {% if siteBgFallback %}
        background-image: url({{ siteBgFallback.first().getUrl('bodyBg') }});
    {% endif %}
{% endif %}
}

.bgblure {
{% if siteBgBlure is defined and siteBgBlure is not empty %}
    {% if siteBgBlure %}
        background-image: url({{ siteBgBlure.first().getUrl('bodyBg') }});
    {% endif %}

{% else %}
    {% if siteBgBlureFallback %}
        background-image: url({{ siteBgBlureFallback.first().getUrl('bodyBg') }});
    {% endif %}
{% endif %}
}

I don't understand why the first three outputs work and the 4th won't work any more.

The backup fields have some pic in there.

Thx for your help :)

3

You can do it like this:

.bg{
    background-image: {{ entry.siteBg.first().getUrl('bodyBg')|default(siteBgFallback.siteBg.first().getUrl('bodyBg)}}
}

And the same for the other one. What you are doing is the following:

  1. Set an item that can be empty (hence the |default).
  2. If the item is empty go to the fallback (the part between the default brackets).

For more info on the default filter check here

3
  • I get scared whenever I see a first().foo, especially when assets are involved. As soon as the file is missing you will get an error, because first() returns null.
    – carlcs
    Jan 19 '17 at 21:04
  • I understand your concerns, however this example is only for demonstrative purposes. You could put an extra default layer to the above statement just for safety or make the fallback required in the CMS.
    – Jan_dh
    Jan 19 '17 at 21:33
  • The file can be deleted, even if the asset field is marked as required.
    – carlcs
    Jan 19 '17 at 21:45
0

My guess is that you need to change this:

{% if siteBgBlureFallback %}
    background-image: url({{ siteBgBlure.first().getUrl('bodyBg') }});
{% endif %}

To this:

{% if siteBgBlureFallback %}
    background-image: url({{ siteBgBlureFallback .first().getUrl('bodyBg') }});
{% endif %}
1
  • Ups, that was a copy error from my side. That don't work's. That is not the problem i'm looking for.
    – The Frog
    Dec 20 '16 at 11:20

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.