Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why to use " | safe" in jinja2 Python [duplicate]

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 %}
like image 240
Muhammad Arslan Maqsood Avatar asked Feb 25 '18 15:02

Muhammad Arslan Maqsood


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 is jinja2templates?

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.

How many delimiters are there in Jinja2?

there are two delimiters to split by here: first it's ",", and then the elements themselves are split by ":".


2 Answers

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.

like image 91
Artsiom Praneuski Avatar answered Oct 01 '22 02:10

Artsiom Praneuski


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.

like image 33
Stephen Rauch Avatar answered Oct 01 '22 00:10

Stephen Rauch