Lir*_* Su 5 ruby liquid jekyll
我知道有一个contains关键字,所以我可以使用:
{% if some_string contains sub_string %}
<!-- do_something -->
{% ... %}
Run Code Online (Sandbox Code Playgroud)
但是如何检查字符串是否以特定子字符串结尾?
我试过这个,但它不起作用:
{% if some_string.endswith? sub_string %}
<!-- do_something -->
{% ... %}
Run Code Online (Sandbox Code Playgroud)
小智 5
通过 Jekyll,我最终编写了一个添加过滤器的小型模块包装器:
module Jekyll
module StringFilter
def endswith(text, query)
return text.end_with? query
end
end
end
Liquid::Template.register_filter(Jekyll::StringFilter)
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
{% assign is_directory = page.url | endswith: "/" %}
Run Code Online (Sandbox Code Playgroud)
作为解决方法,您可以使用该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 %}
Run Code Online (Sandbox Code Playgroud)
如果 some_string 为空或比 sub_string 短,它仍然可以工作,因为切片结果也将为空
| 归档时间: |
|
| 查看次数: |
3643 次 |
| 最近记录: |