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?
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.
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.
Check SafeString, like for example:
from django.utils.safestring import SafeString
...
return context.update({
'html_string': SafeString(html_string),
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With