I'm new to Jinja2 and so far I've been able to do most of what I want. However, I need to use regular expressions and I can't seem to find anything anywhere in the documentation or on teh Googles.
我是Jinja2的新手,到目前为止,我已经能够做我想做的大部分事情。但是,我需要使用正则表达式,我似乎在文档或google上找不到任何东西。
I'd like to create a macro that mimics the behavior of this in Javascript:
我想创建一个宏来模仿Javascript中的行为:
function myFunc(str) {
return str.replace(/someregexhere/, '').replace(' ', '_');
}
which will remove characters in a string and then replace spaces with underscores. How can I do this with Jinja2?
它将删除字符串中的字符,然后用下划线替换空格。我怎么用Jinja2呢?
1 个解决方案
#1
30
There is an already existing filter called replace
that you can use if you don't actually need a regular expression. Otherwise, you can register a custom filter:
如果不需要正则表达式,则可以使用一个名为replace的现有过滤器。否则,您可以注册一个自定义过滤器:
{# Replace method #}
{{my_str|replace("some text", "")|replace(" ", "_")}}
# Custom filter method
def regex_replace(s, find, replace):
"""A non-optimal implementation of a regex filter"""
return re.sub(find, replace, s)
jinja_environment.filters['regex_replace'] = regex_replace
#1
30
There is an already existing filter called replace
that you can use if you don't actually need a regular expression. Otherwise, you can register a custom filter:
如果不需要正则表达式,则可以使用一个名为replace的现有过滤器。否则,您可以注册一个自定义过滤器:
{# Replace method #}
{{my_str|replace("some text", "")|replace(" ", "_")}}
# Custom filter method
def regex_replace(s, find, replace):
"""A non-optimal implementation of a regex filter"""
return re.sub(find, replace, s)
jinja_environment.filters['regex_replace'] = regex_replace