Non-empty checks
Use an
if
statement to check if a variable has a non-null value
Related
See Truthy page for a list of what is truth and falsy. The Truthy section will probably surprise you. As Jekyll doesn’t behave like other languages like Python or JavaScript.
Check variable is defined and not null
In Jekyll, an if
statement on a variable will be truth if:
- The variable is defined (i.e. declared, not missing).
- The variable is not
null
.
{% if my_var %}
{{ my_var }}
{% endif %}
Warning - this check will return true
even for a value that is a zero number, an empty string, or an empty array.
Check that number is non-zero
{% if my_int and my_int != 0 %}
{{ my_int }}
{% endif %}
Check that string is not empty
{% if my_str and my_str != '' %}
{{ my_str }}
{% endif %}
Check that array is not empty
Here we check an array is defined and that it has at least one element.
{% if my_array and my_array.size != 0 %}
{{ my_array | inspect }}
{% endif %}
It is not sufficient to check my_var.size
as a zero value is still truthy.
Example case:
{% if page.playgrounds and page.playgrounds.size != 0 %}
<h3>Online playgrounds</h3>
<ul>
{% for item in page.playgrounds %}
<li>
{{ item.name }}
<li>
{% endfor %}
</ul>
{% endif -%}
If you just had a for
loop, that wouldn’t matter. But if you might want to know an array has values in it so you can render a heading before it.
Detecting nil values with where
filter
From the docs.
Only Jekyll 4.
Using nil
to select posts that either do not have my_prop
defined or my_prop
has been set to nil
explicitly.
{% assign filtered_posts = site.posts | where: 'my_prop', nil %}
Using Liquid’s special literal empty
or blank
to select posts that have my_prop
set to an empty value.
{% assign filtered_posts = site.posts | where: 'my_prop', empty %}