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

4
在Liquid中,可以通过以下方式从一个liquid字符串中删除一个字符X
{{ 'random_string' | remove:'X' }}

例如,可以通过这种方式删除{字符。
但是,通过这种方式删除}字符会导致以下错误。
Liquid syntax error (line 15): Variable '{{ 'random_string' | remove:"}' was not properly terminated with regexp: /\}\}/

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

问题

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


你是否尝试通过在}前面添加\来转义它? - T.Trassoudaine
2个回答

0
一种解决方案是使用url_encode过滤器,然后删除编码的字符串。
{% capture my_variable %}hello}}worl}d{% endcapture %}
{{ my_variable | url_encode | remove: "%7D"}}

0
首先,创建您自己的标签。
<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]+'

输出:

测试!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接