Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string ends with a particular substring in Liquid?

I know there is a contains keyword so I can use:

{% if some_string contains sub_string %}
    <!-- do_something -->
{% ... %}

But how can I check if a string ends with a particular substring?

I've tried this but it won't work:

{% if some_string.endswith? sub_string %}
    <!-- do_something -->
{% ... %}
like image 792
Lirian Su Avatar asked May 04 '16 08:05

Lirian Su


3 Answers

As a workaround you could use the string slice method

  • with as startIndex: some_string length - sub_string length and
  • stringLength: sub_string size
  • and if the result of the slice is the same as the sub_string -> the sub_string is at the end of some_string.

it's a bit clumpy in a liquid template but it would look like:

{% capture sub_string %}{{'subString'}}{% endcapture %}
{% capture some_string %}{{'some string with subString'}}{% endcapture %}

{% assign sub_string_size = sub_string | size %}
{% assign some_string_size = some_string | size %}
{% assign start_index = some_string_size | minus: sub_string_size %}
{% assign result = some_string | slice: start_index, sub_string_size %}

{% if result == sub_string %}
    Found string at the end
{% else %}
    Not found
{% endif %}

and if the some_string is empty or shorter than sub_string it works anyway because the slice result would be empty as well

like image 182
michaPau Avatar answered Nov 15 '22 14:11

michaPau


With Jekyll, I ended up writing a small module-wrapper that adds a filter:

module Jekyll
   module StringFilter
    def endswith(text, query)
      return text.end_with? query
    end
  end
end
  
Liquid::Template.register_filter(Jekyll::StringFilter)

I use it like this:

{% assign is_directory = page.url | endswith: "/" %}
like image 30
pilvikala Avatar answered Nov 15 '22 13:11

pilvikala


We can use another solution with split filter.

{%- assign filename = 'main.js' -%}
{%- assign check = filename | split:'js' -%}

{% if check.size == 1 and checkArray[0] != filename %}
   Found 'js' at the end
{% else %}
   Not found 'js' at the end
{% endif %}

Here we go ^^.

like image 38
v20100v Avatar answered Nov 15 '22 12:11

v20100v