【问题标题】:How can I check if a string ends with a particular substring in Liquid?如何检查字符串是否以 Liquid 中的特定子字符串结尾?
【发布时间】:2016-05-04 08:33:00
【问题描述】:

我知道有一个contains 关键字,所以我可以使用:

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

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

我试过了,但是不行:

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

【问题讨论】:

    标签: ruby jekyll liquid


    【解决方案1】:

    作为一种解决方法,您可以使用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 短,它仍然可以工作,因为切片结果也会为空

    【讨论】:

    • 你为什么用capture而不是assign
    • 我不确定。 Here 它说在某些情况下捕获是/可以更快。我认为capture 对于 some_string 和 sub_string 的定义是有意义的,因为它可能是由其他东西构成的东西。也许对于其余的assign 会更清楚阅读。你怎么看?
    • 在你的情况下,没有append,就像{% assign foobar = "foo" | append: bar %}一样,分配速度提高了20%。从我的角度来看,当您可以使用 assign 时,这可以避免出现不需要的空格或换行符的错误。
    • 没试过这个答案。我使用其他方法并避免检查液体代码中的字符串结尾。
    【解决方案2】:

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

    【讨论】:

    【解决方案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 %}
    

    我们开始吧^^。

    【讨论】:

      【解决方案4】:

      通过@v20100v 扩展答案

      最好在拆分后获取数组中的最后一项,因为字符串可能会出现多次分隔符。

      例如,“test_jscript.min.js”

      类似于以下内容:

      {% assign check = filename | split:'.' | last %}
      
      {% if check == "js" %}
          Is a JS file
      {% else %}
          Is not a JS file
      {% endif %}
      

      【讨论】:

        最近更新 更多