【问题标题】:python - unescape in django templatepython - django 模板中的 unescape
【发布时间】:2012-04-15 21:34:27
【问题描述】:

a = 'abc'

Html 特殊字符在文章时显示。

> {{ a | escape }}

'abc'

当我表明我想逃避时。

> {{ a | escape | safe }}

TemplateSyntaxError: Invalid filter: 'safe'

发生错误。

> from django.utils.safestring import mark_safe

> a = mark_safe(a)

也会出现这个错误。

Django 不让当前不应用到保险箱?

你对如何逃脱有什么想法吗?

(我正在 google-appengine 中开发。)

【问题讨论】:

    标签: django google-app-engine django-templates escaping


    【解决方案1】:

    您的要求并不完全清楚,但您可以使用 autoescape template tag 禁用 Django 的自动转义。例如:

    >>> from django.template import Template, Context
    >>> c = Context(dict(a = '<a href="#fragment">Link</a>'))
    >>> Template("{{ a }}").render(c)
    u'&lt;a href=&quot;#fragment&quot;&gt;Link&lt;/a&gt;'
    >>> Template("{% autoescape off %}{{ a }}{% endautoescape %}").render(c)
    u'<a href="#fragment">Link</a>'
    

    mark_safe 也可以:

    >>> from django.utils.safestring import mark_safe
    >>> Template("{{ a }}").render(Context(dict(a = mark_safe(a))))
    u'<a href="#fragment">Link</a>'
    

    【讨论】:

    • 谢谢。可能我用的是 Django 0.96 版本,用起来好像不行。
    • 如果您要在 App Engine 上使用 mark_safe,请确保导入 google.appengine._internal.django.utils.safestring,否则将无法正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 2015-12-19
    • 1970-01-01
    • 2018-10-22
    • 2013-10-08
    • 1970-01-01
    相关资源
    最近更新 更多