I have a small Jekyll-powered site that uses the default Liquid templating engine. I'm converting it to use Gekyll, which overrides the standard page.date template variable with a Git timestamp, so I need to override the date with a page.original_date value declared in the front matter just for older posts.
In my template, I'd like to be able to do this:
<span class="date">{% page.original_date or page.date | date: "%B %-d, %Y" }}</span>
That doesn't appear to work, so I'm doing this:
<span class="date">
{% if page.original_date %}
{{ page.original_date | date: "%B %-d, %Y" }}
{% else %}
{{ page.date | date: "%B %-d, %Y" }}
{% endif %}
</span>
It's not a big deal, but cumbersome enough to look for a better solution. Does the logic in Liquid allow for a fallback variable like in my first attempt?
In terms of looking for a ternary operator, I think this is the simplest syntax you can use:
{% assign original_date = page.original_date %}
{% unless original_date %}{% assign original_date = page.date %}{% endunless %}
{% unless original_date %}{% assign original_date = date: "%B %-d, %Y" %}{% endunless %}
Not very readable or concise, but at least it works!
{% page.original_date or page.date | date: "%B %-d, %Y" }} logic isn't correct to me in the first place.
or operator is definitely supported in Liquid, but it is a conditional-OR operator performing a logical-OR like other normal programming languages.
However, what you want to is a fallback thing, like ternary operator.
For example, similarly to C#'s ?? Operator or ?: Operator
{% page.original_date ?? page.date | date: "%B %-d, %Y" }}
{% page.original_date ? page.original_date : page.date | date: "%B %-d, %Y" }}
Unfortunately, I don't think it exists in Liquid. See this Ternary operator support isssue at Liquid's issue tracker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With