Why Jekyll's Liquid 'contains' returns a string?
Asked Answered
D

1

7

I try to assign to a variable a true or false value depending on whether a string contains another string. I use the following code:

{% assign external_link = link.href contains '://' %}

For this snippet the external_link's value will be the same as the link.href's value (I checked the value of the external_link with the command {{ external_link }}).

I will get the same result even if I put parenthesizes around the right side:

{% assign external_link = (link.href contains '://') %}

What is the problem, and how can I get a true/false result of the contains expression?

Donatelli answered 21/2, 2017 at 16:51 Comment(0)
T
12

You can use the capture filter tag to get the result of the contains tag:

{% assign link = "http://example.com "%}
{% capture has_link %}{% if link contains '://' %}Yes{% else %}No{% endif %}{% endcapture%}
{{has_link}}

{% assign link = "example.com "%}
{% capture has_link %}{% if link contains '://' %}Yes{% else %}No{% endif %}{% endcapture%}
{{has_link}}

Another option without capture

{% assign link = "http://example.com "%}
{% if link contains '://' %}
{% assign has_link = "yes" %}
{% else %}
{% assign has_link = "no" %}
{% endif %}
{{has_link}}

{% assign link = "example.com "%}
{% if link contains '://' %}
{% assign has_link = "yes" %}
{% else %}
{% assign has_link = "no" %}
{% endif %}
{{has_link}}

Output:

yes

no
Thelen answered 21/2, 2017 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.