代码之家  ›  专栏  ›  技术社区  ›  IP_

在jekyll中有条件地添加数据属性

  •  0
  • IP_  · 技术社区  · 7 年前

    我的博客文章的基本主题是:

       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 
    

    下面是显示条目的my 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: . 我正在寻找一种方法来添加数据源属性,只要它是在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 %}
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   David Jacquel    7 年前

    这里我看到四个案例:

    • post.origin 没有出现在前面: post.origin == null
    • 邮政起源 出现在前面,但没有设置( post.origin: ) =>post.origin==空`
    • 邮政起源 出现在前面,但设置为空字符串( post.origin: "" ) = & gt; post.origin == ""
    • 邮政起源 出现在前面,并设置为有效字符串( post.origin: "toto" ) = & gt; 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 != null .