Here is my situation. This is not a whole code, only the part, where I'm having a problem. At the back end, model coverbackup is populated with files as well as model cover. If I depopulate cover (remove image from entry), I want to load model coverbackup. I was checking over and over, If I got to my file in matrix field correctly, but It seems I have.

Than I've tried to check if elseif statement loads anything on cover=false, I got empty output.

{# Get the slides stored in variable "slides" #}
{% set slides = craft.entries.section('handle').type(['article', 'blog', 'news']).order('RAND()').limit(3) %}

    {% if slides %}
    <ul class="uk-slideshow">

        {% for slide in slides %}  

            {% set cover = slide.coverImage %}
            {% set coverbackup = slide.entryContent %}

                    {% if cover %}    
                        {% for cover in cover %}
                            <div class="uk-panel-teaser">
                                <img class="uk-margin-bottom" src="{{ cover.getUrl('thumb700') }}" alt="{{ cover.title }}">
                        {% endfor %}

                    {% elseif coverbackup %}
                        {% for block in coverbackup %}
                            {% if block.type == "image" %}
                                {% for image in block.images %}
                                    <div class="uk-panel-teaser">
                                        <img class="uk-margin-bottom" src="{{ image.getUrl('thumb700') }}" alt="{{ image.title }}">
                                {% endfor %}
                            {% endif %}
                        {% endfor %}
                    {% endif %}

     {% endfor %}

{% endif %}

The proper conditional statement in this case would be to test for the length property of your Asset field, i.e. cover:

{% if cover | length %}

The reason this works, is that calling slide.coverImage will – as long as the attribute "coverImage" exists for the "slide" model – never return a falsey value, even if there are no files. It will in fact always return an instance of the ElementCriteriaModel class, i.e. an object representing your Asset field.

What the conditional {% if cover | length %} does is to read the length property of the ElementCriteriaModel object. The length property will represent the number of images in the Asset field – if it contains 0 images, the conditional will evaluate to "false" – as the number 0 within a conditional is interpreted as a falsey value. If you prefer, you can also write the statement like this:

{% if cover | length > 0 %}

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.