1

I'm trying to do this:

{% for image in entry.illustration %}
    {% if image | length %}
        <a href="{{ entry.url }}" class="flag__img">
            <img src="{{ image.getUrl }}" alt="{{ entry.altText }}" class="profile__image">
        </a>
    {% else %}  
        <p>No image.</p>        
    {% endif %}
{% endfor %}

Without any luck. What would be a good way of telling craft to do something else if entry.illustration does not have an image defined?

0
3

You may want to try this:

{% for image in entry.illustration %}
  {% if image %}
      <a href="{{ entry.url }}" class="flag__img"><img src="{{ image.getUrl() }}" alt="{{ entry.altText }}" class="profile__image" /></a>
  {% else %}
    <p>No image.</p>
  {% endif %}
{% endfor %}  

(Assuming the altText field is an entry field.) :)

2

If you want to make it a little smaller, you could use a ternary statement, so on your img tag, you could use the following

<img src="{{ image ? image.getUrl : 'http://example.com/image.png' }}" />

So you're full snippet would be

{% for image in entry.illustration %}
        <a href="{{ entry.url }}" class="flag__img">
            <img src="{{ image ? image.getUrl : 'http://example.com/image.png' }}" alt="{{ image.altText ? image.altText : "Default Alt Text" }}" class="profile__image" />

        </a>
{% endfor %}

A ternary statement is basically a shorthand if statement.

{{ (condition is true) ? do this : else do this }}

Also changed entry.altText to image.altText in the for loop. That may be where you are going wrong?

5
  • Thanks. Could you be a bit more specific please? This didn't do much good.
    – osh
    Jul 14 '14 at 13:48
  • edited the above to help you out. Jul 14 '14 at 14:51
  • Thanks for helping out. I now have this, but it still doesn't output the placehold.it image: {% for image in employee.illustration %} <a href="{{ employee.url }}" class="flag__img"> <img src="{{ image ? image.getUrl : 'placehold.it/60x30' }}" alt="{{ image.altText ? image.altText : "Default Alt Text" }}" class="profile__circular" /> </a> {% endfor %}
    – osh
    Jul 14 '14 at 15:32
  • try http:// before it ? Jul 14 '14 at 15:42
  • It actually has http:// before it, just not when I paste the code in here :)
    – osh
    Jul 14 '14 at 15:58
1

I am assuming that illustration is an asset field, and you want to display all the images, or No image if there are none. You can do that with an else clause on the for.

{% for image in entry.illustration %}
  <a href="{{ entry.url }}" class="flag__img">
    <img src="{{ image.getUrl }}" alt="{{ entry.altText }}" class="profile__image">
  </a>
{% else %}
  <p>No image.</p>        
{% endfor %}
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.