将模板variables呈现为HTML
我使用“消息”接口将消息传递给用户,如下所示:
request.user.message_set.create(message=message)  我想在我的{{ message }}variables中包含html,并在不转义模板中的标记的情况下渲染它。 
 如果您不想让HTML转义,请查看safe筛选器和autoescape标记 
  FILTER: {{ 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 
 使用autoescapeclosuresHTML转义: 
 {% autoescape off %}{{ message }}{% endautoescape %} 
你可以像这样在你的代码中渲染一个模板:
 from django.template import Context, Template t = Template('This is your <span>{{ message }}</span>.') c = Context({'message': 'Your message'}) html = t.render(c) 
有关更多信息,请参阅Django文档 。
如果你想对你的文本做更复杂的事情,你可以创build自己的filter,并在返回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> 
这会给你一个不错的结果。
 最简单的方法是使用safefilter: 
 {{ message|safe }} 
查看安全筛选器的Django文档以获取更多信息。
无需在模板中使用filter或标签。 只需使用format_html()将variables转换为html,Django就会自动为您变为closuresvariables。
 format_html("<h1>Hello</h1>")