我是Jinja2的新手,到目前为止,我已经能够完成我想要的大部分工作.但是,我需要使用正则表达式,我似乎无法在文档或谷歌上找到任何东西.
我想在Javascript中创建一个模仿此行为的宏:
function myFunc(str) {
return str.replace(/someregexhere/, '').replace(' ', '_');
}
Run Code Online (Sandbox Code Playgroud)
这将删除字符串中的字符,然后用下划线替换空格.我怎么能用Jinja2做到这一点?
Sea*_*ira 34
replace如果您实际上不需要正则表达式,则可以使用已经存在的过滤器.否则,您可以注册自定义过滤器:
{# Replace method #}
{{my_str|replace("some text", "")|replace(" ", "_")}}
Run Code Online (Sandbox Code Playgroud)
# 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
Run Code Online (Sandbox Code Playgroud)