Jinja2过滤器将自定义标记转换为html [英] Jinja2 filter to convert custom markup to html
问题描述
拥有 autoescape 属性(我想保持这样),我希望用户能够输入一些自定义标记,以便有机会格式化文本。例如, [s] [/ s]
将被翻译成< strong>< / strong>
。我相信正确的方法是写定制的Jinja2过滤器。但是以下内容不起作用:
@ app.template_filter()
@evalcontextfilter
def mark2html (eval_ctx,value)
result = escape(value).replace('[s]','< strong>')
如果eval_ctx.autoescape:
result = Markup )
返回结果
应用于
< div> {{custom_markup_text | mark2html}}< / div>
当在 [s]
字符串,存储在 custom_markup_text 中,它应该转换为< strong>
标签。 AFAIK,标记()功能确保我们信任这个特定的字符串,以便HTML不会在那里转义。过滤器已成功应用, [s]
替换为< strong>
,但仍然被转义。 p>
显然,自定义过滤器<另一方面,Jinja2文档的示例过滤器完美工作:
@ app.template_filter()
@evalcontextfilter
def nl2br(eval_ctx,value):
result = u'\\\
\\\
'.join(u'< p>%s< / p>'%p.replace('\在_paragraph_re.split(escape(value))中,对于p中的p'n','< br> \\\
')
)
如果eval_ctx.autoescape:
result = Markup )
返回结果
我做错了什么?
发现问题。它是双重逃脱的字符串 - 相当愚蠢。
此代码完美无瑕:
@ app.template_filter()
@evalcontextfilter
def mark2html(eval_ctx,value):
result = value.replace('[s]',u'< strong>')
result = result.replace('[/ s]', < / strong>')
如果eval_ctx.autoescape:
result =标记(结果)
返回结果
注意,值不能转义,因为autoescape属性为开。
Having the autoescape property on (I want to keep it that way), I want user to be able to enter some custom markup, to have the opportunity to format text. For example, [s][/s]
will be translated into <strong></strong>
. I believe the right way to do this is to write the custom Jinja2 filter. But the following doesn't work:
@app.template_filter()
@evalcontextfilter
def mark2html(eval_ctx, value):
result = escape(value).replace('[s]','<strong>')
if eval_ctx.autoescape:
result = Markup(result)
return result
When applied to text like
<div>{{ custom_markup_text|mark2html }}</div>
When [s]
is encountered in the string, stored in custom_markup_text, it should be converted to <strong>
tag. AFAIK, Markup() function ensures that we trust this particular string, so that HTML is not escaped there. The filter is successfully applied, [s]
is replaced by <strong>
, but it's still escaped.
Obviously, the autoescaping is done after this custom filter. On the other hand, example filter from Jinja2 documentation works perfectly:
@app.template_filter()
@evalcontextfilter
def nl2br(eval_ctx, value):
result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') \
for p in _paragraph_re.split(escape(value)))
if eval_ctx.autoescape:
result = Markup(result)
return result
What am I doing wrong?
Problem found. It's double escaping the string - rather silly. This code works flawlessly:
@app.template_filter()
@evalcontextfilter
def mark2html(eval_ctx, value):
result = value.replace('[s]',u'<strong>')
result = result.replace('[/s]',u'</strong>')
if eval_ctx.autoescape:
result = Markup(result)
return result
Note, value shouldn't be escaped, as autoescape property is on.
这篇关于Jinja2过滤器将自定义标记转换为html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!