Jinja 2 safe keyword
Jinja 2 safe keyword
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping
--
Chapters
00:00 Question
00:35 Accepted answer (Score 37)
01:01 Answer 2 (Score 32)
01:35 Answer 3 (Score 9)
01:53 Answer 4 (Score 3)
02:19 Thank you
--
Full question
https://stackoverflow.com/questions/1234...
Accepted answer links:
[here]: http://jinja.pocoo.org/docs/templates/#w...
[manual escaping]: http://jinja.pocoo.org/docs/templates/#w...
Answer 2 links:
[http://jinja.pocoo.org/docs/templates/#h...]: http://jinja.pocoo.org/docs/templates/#h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #templateengine #jinja2
#avk47
ACCEPTED ANSWER
Score 46
The safe filter explicitly marks a string as "safe", i.e., it should not be automatically-escaped if auto-escaping is enabled.
The documentation on this filter is here.
See the section on manual escaping to see which characters qualify for escaping.
ANSWER 2
Score 40
Normally text is HTML-escaped (so <b> would be written out as <b>, which would render as <b>).
When you put |safe after something, you're telling the template engine that you have already escaped the text yourself, i.e. "it's safe to render this directly". So it will not do that encoding for you.
For more information: http://jinja.pocoo.org/docs/templates/#html-escaping
ANSWER 3
Score 11
For anyone coming here looking to use the safe filter programmatically: wrap it in a markupsafe.Markup class, on which Jinja2 depends on.
ANSWER 4
Score 6
Expanding on @data's answer, here's an example of using markupsafe.Markup:
import markupsafe
vals = {}
vals["name"] = markupsafe.Markup("<b>Duck</b>, Donald")
html = template.render(vals)
The resulting HTML will show Donald's last name in bold wherever the template contains {{name}}.