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?
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}}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With