One of the things that keeps catching me out when using the Liquid templating
language is how to check if an array
includes a specific string. Essentially I want to use the Ruby include?
method but for Liquid sorta like this:
# Pseudo code - This will NOT work!
{% if post.categories.include? 'foo' %}
Foo
{% endif %}
contains
operator{% if post.categories contains 'foo' %}
Foo
{% endif %}
For some reason I can never remember that this method is called contains
and
not include?
so I end up rooting through the Liquid docs searching for
something that doesn’t exist. And even though it’s clearly shown on the Liquid
operators docs page, I
never remember that it’s an operator and not some kind of where
filter.
You’ll find the contain method in liquid’s source
code
within the Condition
class on the condition.rb
file. It’s currently on line
20
and shows how Ruby’s include?
method is used to make it work.
class Condition
@@operators = {
'==' => ->(cond, left, right) { cond.send(:equal_variables, left, right) },
'!=' => ->(cond, left, right) { !cond.send(:equal_variables, left, right) },
'<>' => ->(cond, left, right) { !cond.send(:equal_variables, left, right) },
'<' => :<,
'>' => :>,
'>=' => :>=,
'<=' => :<=,
'contains' => lambda do |_cond, left, right|
if left && right && left.respond_to?(:include?)
right = right.to_s if left.is_a?(String)
left.include?(right)
else
false
end
end,
}
The contains
Liquid method works for both arrays and strings meaning you can
also do this:
# Given that the category of our post is "foobar"
{% if post.category contains 'foo' %}
Foo
{% endif %}