【问题标题】:dealing with HTML escaped content and writing it as HTML处理 HTML 转义内容并将其编写为 HTML
【发布时间】:2014-05-08 19:43:08
【问题描述】:

我正在将一个遗留项目移植到 django 并且遇到了一个奇怪的数据库状态,一个已被 HTML 转义的归档内容:

<p>
    <strong>The ‘Unbundling’ of Research is a secular, not cyclical, trend as it helps asset managers recognize and reward the value of research more independently</strong>.  In 2002, then-New York Attorney General Eliot Spitzer accused major investment banks of promoting companies' shares in their 

所以当我把它转储到 djnago 时

<p>{{ object.field | safe }}</p>

然后再次转义输出:

&amp;lt;p&amp;gt;

真是令人沮丧。我是 djnago 的新手,我无法将转义的内容转换为流式 html 以获得这种格式:

<p>

谢谢

【问题讨论】:

    标签: python html django django-templates escaping


    【解决方案1】:

    你可以写一个custom unescape filter

    from HTMLParser import HTMLParser    
    from django import template   
    
    register = template.Library()
    
    @register.filter
    def unescape(value):
        return HTMLParser().unescape(value)
    

    这是内部逻辑的演示:

    >>> from HTMLParser import HTMLParser 
    >>> value = '&lt;p&gt;'
    >>> HTMLParser().unescape(value)
    u'<p>'
    

    你可以这样使用它:

    <p>{{ object.field | unescape | safe }}</p>
    

    或者,使用filter模板标签:

    {% filter unescape|safe %}
        {{ value }}
    {% endfilter %}
    

    或者,使用autoescape关闭自动转义:

    {% autoescape off %}
        {{ value | unescape }}
    {% endautoescape %}
    

    【讨论】:

    • 我使用的是第一种格式 {{ object.field | unescape }} 我得到消息过滤器未定义...有什么想法吗?
    • @akaphenom 你把{% load ... %} 放到你的模板顶部了吗?
    • 不,但我现在在 djanogo 自定义模板标签教程中看到了它:docs.djangoproject.com/en/dev/howto/custom-template-tags 我应该很快就有了
    • 也适用于那些不知道放在包中的 ./templatetags/fileName.py 并使用模板中的标签导入 fileName api {% load fileName %}
    猜你喜欢
    • 2018-11-13
    • 1970-01-01
    • 2015-08-30
    • 2019-11-30
    • 2010-10-22
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多