3

I'm trying to output an Asset image if the Main Image field is populated, and if it's not populated, I'd like to output a placeholder image. But I'm having problems getting the conditional to work - it outputs the image in the Assets field, but when the field is empty, it's not outputting the placeholder image. Any ideas on what I'm doing wrong here? Thanks.

{% if entry.mainImage %}
  {% for asset in entry.mainImage %}
    <img src="{{ asset.url }}" alt="{{ asset.title }}" />
  {% endfor %}
{% else %}
  <img src="http://placehold.it/130x130/f5f5f5/ccc.png" height="130" width="130" alt="{{ entry.title }}" />
{% endif %}
  • 1
    Try {% if entry.mainImage|length %} – Brad Bell Jan 20 '15 at 1:12
  • Thanks Brad, that did the job. If you add that as an answer I can mark it as such, otherwise, I'll add it myself tomorrow and steal all your glory (and points). ;-) – Stephen Jan 20 '15 at 1:20
  • 1
    Haha... all yours. I burn my reputation for warmth. – Brad Bell Jan 20 '15 at 1:21
7

Thanks to Brad for the answer, and the solution was to use {% if entry.mainImage|length %} instead of {% if entry.mainImage %} for the conditional. So my working code looked like this:

{% if entry.mainImage|length %}
  {% for asset in entry.mainImage %}
    <img src="{{ asset.url }}" alt="{{ asset.title }}" />
  {% endfor %}
{% else %}
  <img src="http://placehold.it/130x130/f5f5f5/ccc.png" height="130" width="130" alt="{{ entry.title }}" />
{% endif %}

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.