簡體   English   中英

如何檢查字符串是否以 Liquid 中的特定子字符串結尾?

[英]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方法

  • with as startIndex: some_string length - sub_string length
  • stringLength: sub_string size
  • 如果切片的結果與 sub_string 相同 -> sub_string 位於 some_string 的末尾。

它在液體模板中有點結塊,但看起來像:

{% 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM