What is the use of “| safe” when passing variables from Django to React.js?

So from a few articles and few examples I’ve seen, when passing a variable context to javascript, one would use something like:

const variable_name = {{ variable | safe }}

I have tried to google but don’t seem to find any answer. What is the use of “safe” here? And when do we use it? If you have any reference or articles I could refer to, that would be extremely helpful. Thank you so much!

Answer

The filter safe indicates that the variable does not require escaping.

By default, django will escape all ‘potentially unsafe’ characters, such as HTML tokens for example, when rendering a variable into an HTML.

For example, if you have variable var1 = "<b>Hello</b>" then writing this:

 {{ var1 | safe }}

Renders to this HTML:

 <b>Hello</b>

While this:

 {{ var1 }}

Renders to this:

 %3Cb%3EHello%3C%2Fb%3E

So in the final result, in the first case you will see the world Hello in bold, while in the second example you will see just the string <b>Hello</b>.

The escaping is done by default primarily to prevent the XSS attack where the attacker can execute malicious code by passing, for example, a <script> token inside an input to a website.

So as a rule of thumb, you can use the ‘safe’ filter when you know for sure your string has no unsafe tags, for example if you generated this variable without basing it on any user input.

For more info, you can see the official docs: https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#std:templatefilter-safe

Also you can read about XSS attacks, there is really a lot of info on this, just google.