简体   繁体   中英

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.

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 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.

使用autoescape关闭 HTML 转义:

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

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.

The simplest way is to use the safe filter:

{{ message|safe }}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM