1

I'm trying to attach a custom header image for each entry, if none is selected then the default one will be displayed.

  1. contentBuilder is the Matrix field.
  2. imgHeader is an assets block type.
  3. img is the actual field

{% for content in entry.contentBuilder.type('imgHeader') %}

    {% if content.img|length %}
        {{ content.img.first.url }}
    {% else %}
        default jpg
    {% endif %}

{% endfor %}

However this doesn't work. Please advise :)

1

Image are returned as an array so could use either of the following:

{{ content.img[0].url }}

Or set a variable which fetches the asset to then output its fields

{% set asset = content.img.first() %}
{{ asset.url }}

Related: Looping through images in a Asset field type


UPDATE: The line {% if content.img|length %} will always be true because you are checking for existence of the field. You need to instead check that the field has a value using one of the methods below:

{% for content in entry.contentBuilder.type('imgHeader') %}

    {% if content.img[0]|length %}
        {{ content.img[0].url }}
    {% else %}
        default jpg
    {% endif %}

{% endfor %}

or

{% for content in entry.contentBuilder.type('imgHeader') %}

    {% set image = content.img.first() %}

    {% if image|length %}
        {{ image.url }}
    {% else %}
        default jpg
    {% endif %}

{% endfor %}
  • Hi, my version does display the image if it was assigned to the field. The problem is that the whole conditional don't work if there is no field added. – Mark H. May 19 '16 at 20:19

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.