将模板变量渲染为HTML

时间:2011-01-31 07:40:00

标签: django django-templates

我使用'messages'接口将消息传递给用户,如下所示:

request.user.message_set.create(message=message)

我想在我的{{ message }}变量中包含html并在不转义模板中的标记的情况下呈现它。

6 个答案:

答案 0 :(得分:286)

如果您不希望HTML转义,请查看safe过滤器和autoescape标记

过滤器:{{ myhtml |safe }}
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe

标签:{% autoescape off %}{{ myhtml }}{% endautoescape %} http://docs.djangoproject.com/en/dev/ref/templates/builtins/#autoescape

答案 1 :(得分:30)

如果你想对你的文本做一些更复杂的事情,你可以创建自己的过滤器并在返回html之前做一些魔术。 使用如下所示的templatag文件:

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)

然后你可以在模板文件中添加它

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

这会给你带来不错的结果。

答案 2 :(得分:29)

使用autoescape关闭HTML转义:

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

答案 3 :(得分:26)

您可以在代码中渲染模板,如下所示:

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

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

有关详细信息,请参阅Django docs

答案 4 :(得分:16)

最简单的方法是使用safe过滤器:

{{ message|safe }}

查看Django documentation for the safe filter了解详情。

答案 5 :(得分:5)

无需在模板中使用过滤器或标记。 只需使用format_html()将变量转换为html,Django将自动为您的变量关闭转义。

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

点击此处https://docs.djangoproject.com/en/1.9/ref/utils/

相关问题