【问题标题】:How to remove } character from liquid string如何从液体字符串中删除 } 字符
【发布时间】:2022-01-02 23:49:55
【问题描述】:

在 Liquid 中,可以像这样从液体字符串中删除字符 X

{{ 'random_string' | remove:'X' }}

例如{ 字符可以通过这种方式删除。

但是,以这种方式删除 } 字符会产生以下错误,

Liquid syntax error (line 15): Variable '{{ 'random_string' | remove:"}' was not properly terminated with regexp: /\}\}/

这可能与 Liquid 语言中 } 字符的使用有关。

问题

如何从字符串中删除} 字符?

【问题讨论】:

  • 您是否只是尝试通过在 } 前添加 \ 来逃避它?

标签: string character liquid


【解决方案1】:

一种解决方案是使用 url_encode 过滤器,然后删除编码字符串:

{% capture my_variable %}hello}}worl}d{% endcapture %}
{{ my_variable | url_encode | remove: "%7D"}}

【讨论】:

    【解决方案2】:

    您可以将特殊字符分配给对其进行解码的变量,然后将该变量用作过滤器参数

     {% assign curlyBracket = "%7D" | url_decode  %}
     {{ testString | remove: curlyBracket }}
    

    工作示例:

    urldecode相关信息:https://shopify.github.io/liquid/filters/url_decode/

    【讨论】:

      【解决方案3】:

      首先,创建你自己的标签。

      <project>/<app>/templatetags/clean_string.py
      

      将此代码插入其中。

      import re
      
      from django import template
      register = template.Library()
      
      
      @register.filter
      def clean_string(value):
          regex = '[^-_.,!?@%\w\d]+'
          return re.sub(regex, '', value)
      

      之后,在设置中注册...

      <project>/<projectName>/settings.py
      
      'OPTIONS': {
                  'context_processors': [
                      ...
                  ],
                  'libraries': {
                      'clean_string': '<project>.templatetags.clean_string'
                  }
              },
      

      在你的.html模板开头添加标签加载

      {% load clean_string %}

      此过滤器可以应用于任何字符串。

      例如:

      {{ '[tes{t}!'|clean_string }}
      

      过滤器可以在变量中调整...

      regex = '[^-_.,!?@%\w\d]+'
      

      输出:

      测试!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-04
        • 1970-01-01
        • 2021-10-26
        • 2015-12-01
        • 2010-10-13
        相关资源
        最近更新 更多