Rendering a template variable as HTML Rendering a template variable as HTML django django

Rendering a template variable as HTML


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


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 templatefrom django.utils.safestring import mark_saferegister = template.Library()@register.filterdef 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.


You can render a template in your code like so:

from django.template import Context, Templatet = Template('This is your <span>{{ message }}</span>.')c = Context({'message': 'Your message'})html = t.render(c)

See the Django docs for further information.