1

My basic YAML Front Matter for blog posts looks as:

   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 

Here is my index.html to display entries:

<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>

The problem is: Some posts are supposed to have no origin value, like origin:. And I am looking for a way to add data-origin attribute only if it's value specified in YAML Front Matter.

Liquid give following option:

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

Is there any way to use it inside of html tag? In my case I expect something like this:

 {% for post in site.posts %}

 <li  
     {% if post.origin has value %}
         data-origin="{{ post.origin }}"
     {% endif %}">      
</li>
{% endfor %}
IP_
  • 676
  • 5
  • 18

1 Answers1

1

Here I see four cases :

  • post.origin is not present in front matter : post.origin == null
  • post.origin is present in front matter, but not set (post.origin:) => post.origin == null`
  • post.origin is present in front matter, but set to empty string (post.origin: "") => post.origin == ""
  • post.origin is present in front matter, and set to valid string (post.origin: "toto") => post.origin == "toto"

Results are conform to Truthy and falsy Liquid documentation.

From there, using logical liquid operators, we can build a condition like :

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

Note that post.origin means post.origin != null.

David Jacquel
  • 51,670
  • 6
  • 121
  • 147