我是 Jinja2 的新手,到目前为止,我已经能够做大部分我想做的事情。但是,我需要使用正则表达式,我似乎在文档或谷歌的任何地方都找不到任何东西。
我想创建一个模仿 Javascript 中这种行为的宏:
function myFunc(str) {
return str.replace(/someregexhere/, '').replace(' ', '_');
}
这将删除字符串中的字符,然后用下划线替换空格。我怎么能用 Jinja2 做到这一点?
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