Rendering a template variable as HTML

Rendering a template variable as HTML

I use the 'messages' interface to pass messages to user like this:
request.user.message_set.create(message=message)

I would like to include html in my {{ message }} variable and render it without escaping the markup in the template.

Solutions/Answers:

Answer 1:

If you don’t want the HTML to be escaped, look at the safe filter and the autoescape tag:

safe:

{{ myhtml |safe }}

autoescape:

{% autoescape off %}
    {{ myhtml }}
{% endautoescape %}

Answer 2:

If you want to do something more complicated with your text you could create your own filter and do some magic before returning the html.
With a templatag file looking like this:

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
def do_something(title, content):

    something = '<h1>%s</h1><p>%s</p>' % (title, content)
    return mark_safe(something)

Then you could add this in your template file

<body>
...
    {{ title|do_something:content }}
...
</body>

And this would give you a nice outcome.

Answer 3:

Use the autoescape to turn HTML escaping off:

{% autoescape off %}{{ message }}{% endautoescape %}

Answer 4:

You can render a template in your code like so:

from django.template import Context, Template
t = Template('This is your <span>{{ message }}</span>.')

c = Context({'message': 'Your message'})
html = t.render(c)

See the Django docs for further information.

Answer 5:

The simplest way is to use the safe filter:

{{ message|safe }}

Check out the Django documentation for the safe filter for more information.

Answer 6:

No need to use the filter or tag in template.
Just use format_html() to translate variable to html and Django will automatically turn escape off for you variable.

format_html("<h1>Hello</h1>")

Check out here https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html

References