我知道有一个
contains
关键字,所以我可以使用:
{% if some_string contains sub_string %}
<!-- do_something -->
{% ... %}
但是如何检查字符串是否以特定子字符串结尾?
我已经尝试过,但它不起作用:
{% if some_string.endswith? sub_string %}
<!-- do_something -->
{% ... %}
使用 Jekyll,我最终编写了一个添加过滤器的小型模块包装器:
module Jekyll
module StringFilter
def endswith(text, query)
return text.end_with? query
end
end
end
Liquid::Template.register_filter(Jekyll::StringFilter)
我这样使用它:
{% assign is_directory = page.url | endswith: "/" %}
作为解决方法,您可以使用
string slice
方法
startIndex: some_string length - sub_string length
和 stringLength: sub_string size
在液体模板中有点块状,但它看起来像:
{% 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 %}
如果 some_string 为空或比 sub_string 短,它仍然可以工作,因为切片结果也将为空
我们可以使用另一种带有
split
过滤器的解决方案。
{%- 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 %}
我们出发吧^^.
分割后最好获取数组中的最后一项,因为字符串可能会多次出现分隔符,
例如“test_jscript.min.js”。
类似下面的内容:
{% assign check = filename | split:'.' | last %}
{% if check == "js" %}
Is a JS file
{% else %}
Is not a JS file
{% endif %}