如何检查字符串是否以 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 方法

  • 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-wrapper 添加了一个过滤器:

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 %}