【问题标题】:Jekyll liquid if statement confusionJekyll 液体 if 语句混淆
【发布时间】:2024-01-18 12:45:01
【问题描述】:

我正在尝试根据我的降价帖子的液体标题使 if 语句起作用,如果变量设置为 true,则执行一件事,否则,如果它不存在,则执行另一件事。只是似乎无法让它正常工作。

我尝试将 if 语句更改为 {% unless %}。尝试!= false 的不同组合并交换图像代码。

{% capture banner %}{{ page.banner }}{{ post.banner }}{% endcapture %}
{% capture no-border %}{{ page.no-border }}{{ post.no-border }}{% endcapture %}
{% capture title %}{{ page.title }}{{ post.title }}{% endcapture %}

{% if banner != "" %}
    {% if no-border == true %}
    <img class="center no-border" src="{{ banner }}" alt="{{ title }}"/><br/>
    {% else %}
    <img class="center" src="{{ banner }}" alt="{{ title }}"/><br/>
    {% endif %}
{% endif %}

我希望看到:如果 no-border 在 markdown 文件的液体部分设置为 true,则删除横幅图像的边框。

【问题讨论】:

    标签: html if-statement logic jekyll liquid


    【解决方案1】:

    您的捕获标签,没有page.no-borderpost.no-border,返回一个空字符串,它的计算结果为真,因为除了falsenil 之外,liquid 中的所有值都是真实的。试试这个(或类似的东西):

    {% capture banner %}{{ page.banner }}{{ post.banner }}{% endcapture %}
    {% capture title %}{{ page.title }}{{ post.title }}{% endcapture %}
    
    {% if page.banner or post.banner %}
        {% if page.no-border or post.no-border %}
            <img class="center no-border" src="{{ banner }}" alt="{{ title }}"/><br/>
        {% else %}
            <img class="center" src="{{ banner }}" alt="{{ title }}"/><br/>
        {% endif %}
    {% endif %}
    

    这一切都未经测试,您可以通过几种不同的方式完成。

    编辑:澄清

    详细说明:

    capture 是一个函数。它评估内部的任何内容,并将其作为字符串存储在变量中。如果内容为nil(无),则返回一个空字符串("")。

    在编程中,每个值都被认为是“真”或“假”。这意味着(除其他外)当放置在if 语句中时,真值将执行该语句而假值不会。以整数值 1 为例;在大多数语言中,这是一个真实的值,所以

    if 1
      puts 'hello world'
    end
    

    将打印'hello world'到控制台。 nil 一般是假值,所以

    if nil
      puts 'hello world'
    end
    

    什么都不做。

    究竟哪些值是真值或假值取决于编程语言。 在 Liquid 中,除了nilfalse 之外,一切都是真实的capture 总是返回一个字符串,并且所有字符串,即使是空字符串,都是真实的。

    如果你这样写:

    {% if "" %}
    <img class="center no-border" src="{{ banner }}" alt="{{ title }}"/><br/>
    {% else %}
    <img class="center" src="{{ banner }}" alt="{{ title }}"/><br/>
    {% endif %}
    

    您将始终获得无边框版本。将if 语句替换为if "true"if true,您将得到相同的结果。

    【讨论】:

    • 这似乎行得通。如果捕获标签应该从同一页面拉出并发布标签,为什么它不能工作?
    • 我在答案中添加了详细的解释。希望对您有所帮助!