xpa*_*nta 171 django django-templates
我使用'messages'接口将消息传递给用户,如下所示:
request.user.message_set.create(message=message)
我想在我的{{ message }}变量中包含html 并在不转义模板中的标记的情况下呈现它.
Yuj*_*ita 309
如果您不希望HTML转义,请查看safe过滤器和autoescape标记
过滤器:http:safe
//docs.djangoproject.com/en/dev/ref/templates/builtins/#safe
标签:http:autoescape
//docs.djangoproject.com/en/dev/ref/templates/builtins/#autoescape
Goo*_*nja 33
如果你想对你的文本做一些更复杂的事情,你可以创建自己的过滤器并在返回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>
这会给你一个很好的结果.
mip*_*adi 28
使用它autoescape来关闭HTML转义:
{% autoescape off %}{{ message }}{% endautoescape %}
Mar*_*row 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文档.
Mar*_*row 15
最简单的方法是使用safe过滤器:
{{ message|safe }}
有关更多信息,请查看Django文档以获取安全过滤器.
无需在模板中使用过滤器或标签.只需使用format_html()将变量转换为html,Django将自动为您的变量关闭转义.
format_html("<h1>Hello</h1>")
点击这里https://docs.djangoproject.com/en/1.9/ref/utils/
| 归档时间: | 
 | 
| 查看次数: | 140210 次 | 
| 最近记录: |