Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja 2 safe keyword

I have a little problem understanding what an expression like {{ something.render() | safe }} does .

From what I have seen, without the safe keyword it outputs the entire html document, not just the true content.

What I would like to know, is what it actually does, how it functions .

like image 427
coredump Avatar asked Sep 09 '12 17:09

coredump


People also ask

What is safe in Jinja2?

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.

What are Jinja tags?

Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox. It is a text-based template language and thus can be used to generate any markup as well as source code. Jinja. Original author(s) Armin Ronacher.


2 Answers

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.

like image 75
imm Avatar answered Sep 20 '22 08:09

imm


Normally text is HTML-escaped (so <b> would be written out as &lt;b&gt;, 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

like image 44
dkamins Avatar answered Sep 23 '22 08:09

dkamins