1

My entry has a custom field to set a social image for Facebook.

In the entry template, I'm defining the output like so:

{% set social_image = "" %}
  {% for image in entry.metaImage %}
    {% set social_image = image.getUrl() %}
  {% endfor %}

Then in the layout I have this

<meta property="og:image" content="{% if social_image is defined %}{{ social_image }}{% endif %}" />

and this works great. However, when that field hasn't been, I want to fallback to a custom field that will always have an image set.

I tried to change the layout to {% if social_image is not null %}{{ social_image }}{% else %}{{ social_image_fallback }}{% endif %} setting social_image_fallback within the entry template of course, but that outputs a null value.

I originally had {% if social_image is defined %} but of course if defined would always evaluate to true.

I'm missing something simple here right?

2

Try {{ social_image|default(social_image_fallback) }}. I've had good results using Twig's default filter over testing variables, even with multiple fallbacks. (like this).

1

I'd use the length filter to see if there is an image and then access it using the first() method:

{% if entry.metaImage|length %}
    {% set social_image = entry.metaImage.first().getUrl() %}
{% else %}
    {% set social_image = '/assets/img/social_image.jpg' %}
{% endif %}

If you prefer ternary syntax it would be like so:

{% set social_image = entry.metaImage|length ? entry.metaImage.first().getUrl() : '/assets/img/social_image.jpg' %}

Using it like so you separate logic and output in your template.

1

If you use defined it'll always be true because you at the minimum are defining an empty string. not null won't work because a null is different from a false condition (which an empty string matches).

@mike-pepper and @carlcs both have good suggestions for getting what you need. My personally suggestion would be:

{% set social_image = "" %}
{% for image in entry.metaImage %}
    {% set social_image = image.getUrl() %}
{% else %}
    {% set social_image = fallbackField.first().getUrl() %}
{% endfor %}

That way you can just output social_image.

  • Why loop the images and overwrite the var with each iteration? – carlcs May 7 '15 at 12:54
  • Thanks Bryan. I misunderstood another post about is defined and is not null – Steven Grant May 7 '15 at 12:58

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.