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

问题描述 投票:0回答:4

我知道有一个

contains
关键字,所以我可以使用:

{% if some_string contains sub_string %}
    <!-- do_something -->
{% ... %}

但是如何检查字符串是否以特定子字符串结尾?

我已经尝试过,但它不起作用:

{% if some_string.endswith? sub_string %}
    <!-- do_something -->
{% ... %}
ruby jekyll liquid
4个回答
6
投票

使用 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: "/" %}

4
投票

作为解决方法,您可以使用

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 短,它仍然可以工作,因为切片结果也将为空


3
投票

我们可以使用另一种带有

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

我们出发吧^^.


2
投票

扩展@v20100v的答案

分割后最好获取数组中的最后一项,因为字符串可能会多次出现分隔符,
例如“test_jscript.min.js”。

类似下面的内容:

{% assign check = filename | split:'.' | last %}

{% if check == "js" %}
    Is a JS file
{% else %}
    Is not a JS file
{% endif %}
© www.soinside.com 2019 - 2024. All rights reserved.