11

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 %}
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

2 Answers2

12

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.

Artsiom Praneuski
  • 2,259
  • 16
  • 24
5

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.

Community
  • 1
  • 1
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135