Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mark strings as "Safe" in a view (or the template) in Jinja2?

Typically when you want to mark string output as safe in Jinja2 you do something like this:

{{ output_string|safe() }}

However, what if output_string is always safe? I don't want to repeat myself every time by using the safe filter.

I have a custom filter called "emailize" that preps urls for output in an email. The ampersands always seem to become escaped. Is there a way in my custom filter to mark the output as safe?

like image 430
sotangochips Avatar asked Aug 13 '09 02:08

sotangochips


People also ask

What is safe filter 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 does safe do in Django template?

Django Templates are safe-by-default, which means that expressions are HTML-escaped by default. However, there are cases where expressions are not properly escaped by default: If your template includes JavaScript, then any expression inside the JavaScript should be JavaScript-escaped and not HTML-escaped.


2 Answers

Check SafeString, like for example:

from django.utils.safestring import SafeString
...
return context.update({
        'html_string': SafeString(html_string),
})
like image 55
Wernight Avatar answered Nov 22 '22 05:11

Wernight


Use the Markup class:

class jinja2.Markup([string])

Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped.

like image 26
ars Avatar answered Nov 22 '22 07:11

ars