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?

Steven Grant
  • 1,855
  • 13
  • 27

3 Answers3

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).

Mike Pepper
  • 4,391
  • 17
  • 26
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.

carlcs
  • 36,220
  • 5
  • 62
  • 139
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.

Bryan Redeagle
  • 4,065
  • 13
  • 27