Reputation: 4710
I have a string I want to escape and then add only specific html tags before printing it in jinja. This is what I'm trying to do:
{{ user.info | e | nl2br | safe }}
So essentially I want to convert new lines to <br/>
but escape every html tag provided by user. This doesn't seem to work, the <br/>
tags are also getting escaped. How can I achieve such behavior in Jinja?
Upvotes: 2
Views: 1048
Reputation: 4710
Okay, I found a solution, it seems that escape actually returns a Markup object, so calling safe on it doesn't help. I had to define a custom filter:
@app.template_filter('escape_custom')
def escape_custom(string):
string = str(jinja2.escape(string))
return jinja2.Markup(string.replace('\n', '<br/>\n'))
Upvotes: 4