mark_safe无法正常工作/仍在simple_tag中转义

sco*_*ven 7 django django-templates

我使用的是Django 1.3,我有一个simple_tag,我需要返回一些未转义的HTML,无论我做什么,它仍在&和 和我的| 到%7C。

from django import template
from django.template import loader, Context
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag()
def show_stuff(arg1=None, arg2=None, arg3='someconstant'):

    # Do some stuff

    if someconstant == 'somevalue':
        template_name = 'template1.html'
    else:
        template_name = 'template2.html'

    template = loader.get_template(template_name)
    html = template.render(Context( {'myvar': myvar,} ))
    html = mark_safe(html)
    print type(html)
    return html
Run Code Online (Sandbox Code Playgroud)

打印声明显示

<class 'django.utils.safestring.SafeUnicode'>
Run Code Online (Sandbox Code Playgroud)

从我的理解来看,这是不应该逃脱的。我在模板中调用该标签,如下所示:

{% show_stuff 'arg1' 'arg2' 'arg3' %}
Run Code Online (Sandbox Code Playgroud)

帮助将不胜感激。

更新:从下面的注释中尝试了以下内容。没有返回错误,但仍然转义了HTML:

    ...
    template = loader.get_template(template_name)
    html = template.render(Context( {'myvar': myvar,} ))
    html = mark_safe(html)
    print type(html)
    return html
show_stuff().is_safe=True
Run Code Online (Sandbox Code Playgroud)

还尝试将template1.html和template2.html的内容包装在

{% autoescape off %}
template html contents with & and |
{% endautoescape %}
Run Code Online (Sandbox Code Playgroud)

然后使用autoescape标签将templatetag调用包装起来。没有成功

man*_*nit 6

老线程,但我最近遇到了同样的问题。我让它在 python 3.6 上工作。将简单标签的值分配给变量txt,并使用模板标签“{{”输出txt,并向txt添加安全过滤器。

{% get_contentvalue user "htmlabout" as txt %}
{{txt|safe}}
Run Code Online (Sandbox Code Playgroud)


ser*_*ach 3

在与问题作者的讨论中,我们发现这些字符实际上并没有被转义。Scoopseven(作者)使用 Firefox 上下文菜单中的“显示选择源”选项查看了源 html。在这种情况下,会显示转义字符。