ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Django的消息中内嵌HTML

Django的消息中内嵌HTML

原创 Linux操作系统 作者:jieforest 时间:2012-07-01 15:51:51 0 删除 编辑
Problem

You want to embed HTML within a message using Django's messages framework.

This is a reasonably common requirement - for instance, it's common to want to include a link within the message, perhaps pointing the user towards a sign-in or registration page.
This problem exists as of Django 1.4 but may be solved within the framework in later versions.

Solution

Use the extra_tags keyword argument to pass a flag indicating that the message is safe for rendering without escaping. For example:

CODE:

1.from django.contrib import messages
2.
3.def some_view(request):
4....
5.messages.success(request,
6.'Here is a link.',
7.extra_tags='safe')Then use some simple template logic to determine whether to use the safe filter:

CODE:

01.

    02.{% for message in messages %}
    03.

  • 04.{% if 'safe' in message.tags %}
    05.{{ message|safe }}
    06.{% else %}
    07.{{ message }}
    08.{% endif %}
    09.

  • 10.{% endfor %}
    11.

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/301743/viewspace-734245/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-04-23

  • 博文量
    441
  • 访问量
    602348