239

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.

xpanta
  • 8,124
  • 15
  • 60
  • 104

7 Answers7

450

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 %}
daaawx
  • 3,273
  • 2
  • 17
  • 16
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
42

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Goose Ninja
  • 710
  • 5
  • 12
39

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.

Marcus Whybrow
  • 19,578
  • 9
  • 70
  • 90
38

Use the autoescape to turn HTML escaping off:

{% autoescape off %}{{ message }}{% endautoescape %}
mipadi
  • 398,885
  • 90
  • 523
  • 479
18

The simplest way is to use the safe filter:

{{ message|safe }}

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

Marcus Whybrow
  • 19,578
  • 9
  • 70
  • 90
13

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

Erik Kalkoken
  • 30,467
  • 8
  • 79
  • 114
NorWay
  • 271
  • 3
  • 9
2

The safe filter did the work for me. Using {{data|safe}} includes the html as it is.

Atit Bimali
  • 45
  • 1
  • 7