I am following a Flask tutorial where he is using " | safe " in jinja2 template. Why do we need this pipe symbol and safe?
without using safe it prints all html tags.
By using | safe
, it shows proper formatting. Why does it work this way?
Below is the jinja2 code:
{% extends "layout.html" %}
{% block body %}
<h1>{{article.title}}</h1>
<small>Written by {{article.author}} on {{article.create_date}}</small>
<hr>
<div>
{{article.body | safe}}
</div>
{% endblock %}
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.
Jinja. Jinja2 is a Python library that allows us to build expressive and extensible templates. It has special placeholders to serve dynamic data. A Jinja template file is a text file that does not have a particular extension.
there are two delimiters to split by here: first it's ",", and then the elements themselves are split by ":".
With | safe
Jinja2 will print symbols as they are in your variable, that means that it won't translate "dangerous" symbols into html entities (that Jinja2 does by default to escape "dangerous" ones). Use this option if you trust variable's content because in opposite case there can be vulnerabilities for example XSS.
From the DOCS:
When generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML. There are two approaches:
- manually escaping each variable; or
- automatically escaping everything by default.
Jinja supports both.
In the automatically escaping everything by default mode, to mark content as safe, and therefore not in need of escaping, use the filter:
| safe
Working with automatic escaping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With