How do you mark strings as “Safe” in a view (or the template) in Jinja2?
-
13-09-2019 - |
Question
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?
Solution
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.
OTHER TIPS
Check SafeString, like for example:
from django.utils.safestring import SafeString
...
return context.update({
'html_string': SafeString(html_string),
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow