why to use “ | safe” in jinja2 Python [duplicate]

◇◆丶佛笑我妖孽 提交于 2021-02-07 06:50:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!