Django的訊息中內嵌HTML

jieforest發表於2012-07-01
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部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-734245/,如需轉載,請註明出處,否則將追究法律責任。

相關文章