9

Sorry, this is kind of a newbie question, but I can't figure out how to loop trough all images in one image asset field supporting multiple images.

The only way I have been able to output anything without an error, is this:

{% set asset = entry.wireframeImages.first() %}

{% if asset %}
    {{ asset.url }}
{% endif %}

But as you can see, only the first image is printed out.

How can I loop trough all images from this field?

I have been reading trough this page, but can't figure out how to do this simple task.

Thanks

10

An Asset field – like all relational fields, including Entries, Categories etc – always return an array-like object which is an instance of a class called ElementCriteriaModel. To output the actual file data, this means you have to loop on the field, e.g.:

{% for asset in entry.wireframeImages %}
    <img src="{{ asset.getUrl() }}" />
{% endfor %}

The above is true even if there's 1 Asset selected in the field, or 100.

The cool thing about the for loop in Twig is that it won't throw an error if you attempt to loop on an empty array or object. This means that you don't have to wrap the loop in an {% if %} statement to take care of cases where the Asset field may be empty. Moreover, you can add an {% else %} statement to the for loop, which will be executed if the field is in fact empty:

{% for asset in entry.wireframeImages %}
    <img src="{{ asset.getUrl() }}" />
{% else %}
    <p>Nope, no images here :(</p>
{% endfor %}

In situations where your Asset field is limited to 1 file, a loop may seem like overkill – then you can use

{% set asset = entry.wireframeImages.first %}

to get the first (and only) file. Keep in mind though, that if the Asset field is empty, calling first on it will in fact produce an error. To get around this, you can use the default filter to add a default value to the variable and suppress the error. In these cases you have to have a conditional testing the value as well, though – so the amount of code is about the same as just using a for loop:

{% set asset = entry.wireframeImages.first|default(false) %}
{% if asset %}
    <img src="{{ asset.getUrl() }}" />
{% endif %}

Note that first isn't the only method available to ElementCriteriaModel instances, check out the official docs to read more about it.

| improve this answer | |
3

Got a working solution:

{% set images = entry.wireframeImages %}
{% if images | length %}
  <div class="row mbb">
    {% for image in images %}
      <div class="col l3 m4 s6">
        <img class="responsive-img mt bordered" src="{{ image.getURL() }}">
      </div>
    {% endfor %}
  </div>
{% endif %}
| improve this answer | |

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.