【问题标题】:Conditionally add data-attributes in Jekyll在 Jekyll 中有条件地添加数据属性
【发布时间】:2018-11-09 15:47:02
【问题描述】:

我的博客文章基本 YAML Front Matter 如下所示:

   layout: post
   title:  'Crepes'
   permalink: /crepes/
   src: '/assets/images/crepes.jpg' 
   date:   2018-05-24 21:41:00
   origin: http//...
   ingredients: 
    - ingredient1: amount
    - ingredient2: amount 

这是我的 index.html 来显示条目:

<ul>
{% for post in site.posts %}

<li data-title='{{ post.title }}' data-origin="{{ post.origin }}"
    data-src="{{ post.src | prepend: relative_url}}" 
    data-content='{ "ingredients": {{ post.ingredients | jsonify }} }'>

    <a href="{{ site.baseurl }}{{ post.url }}">
        <img src="{{ post.src | prepend: relative_url }}" alt={{ post.title }}/>
    </a>

</li>
{% endfor %}
</ul>

问题是: 有些帖子应该没有原始值,例如origin:。而且我正在寻找一种方法来添加 data-origin 属性,前提是它是在 YAML Front Matter 中指定的值。

液体提供以下选项:

{% if condition %}
    <li>....</li>
{% endif %}

有没有办法在 html 标签中使用它?就我而言,我希望是这样的:

 {% for post in site.posts %}

 <li  
     {% if post.origin has value %}
         data-origin="{{ post.origin }}"
     {% endif %}">      
</li>
{% endfor %}

【问题讨论】:

    标签: if-statement yaml jekyll liquid yaml-front-matter


    【解决方案1】:

    这里有四个案例:

    • post.origin 没有出现在前面的问题中: post.origin == null
    • post.origin 出现在前面,但未设置 (post.origin:) => post.origin == null`
    • post.origin 出现在前面,但设置为空字符串 (post.origin: "") => post.origin == ""
    • post.origin 出现在前面,并设置为有效字符串 (post.origin: "toto") => post.origin == "toto"

    结果符合Truthy and falsy Liquid documentation

    从那里,使用logical liquid operators,我们可以构建如下条件:

    <li
      {% if post.origin and post.origin != "" %}
         data-origin="{{ post.origin }}"{% endif %}>
    </li>
    

    注意post.origin 表示post.origin != null

    【讨论】:

      猜你喜欢
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 2021-01-21
      • 2019-04-13
      • 1970-01-01
      • 2021-07-15
      相关资源
      最近更新 更多