0

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?

4

2 回答 2

6

在寻找三元运算符方面,我认为这是您可以使用的最简单的语法:

{% 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 %}

不是很可读或简洁,但至少它有效!

于 2017-03-23T07:30:02.870 回答
3

{% page.original_date or page.date | date: "%B %-d, %Y" }}首先,逻辑对我来说是不正确的。

orLiquid 绝对支持运算符,但它是一个条件 OR 运算符,它像其他普通编程语言一样执行逻辑或。

但是,你想要的是一个后备的东西,比如三元运算符。

例如,类似于 C# 的?? 运算符?:运算符

{% page.original_date ?? page.date | date: "%B %-d, %Y" }}
{% page.original_date ? page.original_date : page.date | date: "%B %-d, %Y" }}

不幸的是,我认为它不存在于 Liquid 中。在 Liquid 的问题跟踪器中查看此三元运算符支持问题。

于 2013-07-31T23:07:58.137 回答