Rendering a template variable as HTML

DjangoDjango Templates

Django Problem Overview


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.

Django Solutions


Solution 1 - Django

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 %}

Solution 2 - Django

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.

Solution 3 - Django

Use the autoescape to turn HTML escaping off:

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

Solution 4 - Django

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.

Solution 5 - Django

The simplest way is to use the safe filter:

{{ message|safe }}

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

Solution 6 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxpantaView Question on Stackoverflow
Solution 1 - DjangoYuji 'Tomita' TomitaView Answer on Stackoverflow
Solution 2 - DjangoGoose NinjaView Answer on Stackoverflow
Solution 3 - DjangomipadiView Answer on Stackoverflow
Solution 4 - DjangoMarcus WhybrowView Answer on Stackoverflow
Solution 5 - DjangoMarcus WhybrowView Answer on Stackoverflow
Solution 6 - DjangoNorWayView Answer on Stackoverflow