[英]How can I check if a string ends with a particular substring in Liquid?
我知道有一個contains
關鍵字,所以我可以使用:
{% if some_string contains sub_string %}
<!-- do_something -->
{% ... %}
但是如何檢查字符串是否以特定子字符串結尾?
我試過這個,但它不起作用:
{% if some_string.endswith? sub_string %}
<!-- do_something -->
{% ... %}
作為一種解決方法,您可以使用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 短,它仍然可以工作,因為切片結果也將為空
使用 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: "/" %}
我們可以使用帶有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 %}
我們來了^^。
通過@v20100v 擴展答案
最好在拆分后獲取數組中的最后一項,因為字符串可能多次出現分隔符。
例如,“test_jscript.min.js”
類似於以下內容:
{% assign check = filename | split:'.' | last %}
{% if check == "js" %}
Is a JS file
{% else %}
Is not a JS file
{% endif %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.