Conditional operation with Liquid


Problem

I saw an opportunity to improve my Liquid markup when I was updating the following Jekyll layout:

<time datetime="{{ page.date | date_to_xmlschema }}">
  {{ page.date | date: "%b %d, %Y" }}
</time>

I added a new FrontMatter field updated and I wanted to conditionally render it:

---
date:    2017-09-23 20:36:38
updated: 2019-08-25 14:16:02 # optional
---

First Attempt

My first attempt was to use control flow:

{% if page.updated %}
  <time datetime="{{ page.updated | date_to_xmlschema }}">
    {{ page.updated | date: "%b %d, %Y" }}
  </time>
{% else %}
  <time datetime="{{ page.date | date_to_xmlschema }}">
    {{ page.date | date: "%b %d, %Y" }}
  </time>
{% endif %}

However, it didn’t feel that DRY so I tried assigning a ternary operator to a variable:

{% assign date = page.updated ? page.updated : page.date %}

Unfortunately, that didn’t work.

Final Solution

I did some digging and discovering a comment that recommended the default filter:

{{ a | default: b }}

That ended up working nicely for my use case so I was able to refactor my markup to the following:

{% assign date = page.updated | default: page.date %}
<time datetime="{{ date | date_to_xmlschema }}">
  {{ date | date: "%b %d, %Y" }}
</time>


If you enjoyed this post, please consider supporting this site!