问题
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 %}
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/48975383/why-to-use-safe-in-jinja2-python