Having the autoescape property (I want to save it this way), I want the user to be able to enter some special markup to be able to format the text. For example, [s][/s]will be translated to <strong></strong>. I believe the right way to do this is to write a custom Jinja2 filter. But the following does not 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 type
<div>{{ custom_markup_text|mark2html }}</div>
When [s]found in a string stored in custom_markup_text , it should be converted to a tag <strong>. The AFAIK function, Markup () ensures that we trust this particular line so that HTML is not deleted there. The filter is successfully applied, [s]replaced by <strong>, but it is still shielded.
Obviously, auto-protection is performed after this custom filter. On the other hand, the filter example from the Jinja2 documentation works fine:
@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?
source
share