Ankit
Ankit

Reputation: 4710

Escaping string and then adding html tags in jinja

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

Answers (1)

Ankit
Ankit

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

Related Questions