如何禁用Django';从视图中自动转义?

如何禁用Django';从视图中自动转义?,django,django-templates,escaping,Django,Django Templates,Escaping,Django说有3种方法可以关闭自动转义: 在变量后面使用| safe 在块内使用{%autoescape on%}和{%endautoescape%} 使用上下文,如Context=Context({'message':message},autoescape=False) (1) (2)工作良好。但我有这样一种情况:我有生成纯文本推送通知的模板,我有大量的模板要构建和维护。我可以遍历并将{%autoescape on%}和{%endautoescape%}标记放在所有这些标记中,但是(3)应该

Django说有3种方法可以关闭自动转义:

  • 在变量后面使用
    | safe
  • 在块内使用
    {%autoescape on%}
    {%endautoescape%}
  • 使用上下文,如
    Context=Context({'message':message},autoescape=False)
  • (1) (2)工作良好。但我有这样一种情况:我有生成纯文本推送通知的模板,我有大量的模板要构建和维护。我可以遍历并将
    {%autoescape on%}
    {%endautoescape%}
    标记放在所有这些标记中,但是(3)应该允许我在视图中的一行中完成

    模板:

    {% block ios_message %}{{message}}{% endblock %}
    
    观点:

    message = u"'&<>"
    context = Context({'message': message}, autoescape=False)
    render_block_to_string(template_name, 'ios_message', context)
    
    block_render.py的代码来自此处:。从那里开始,我就按原样使用它


    有人知道会给你什么吗?

    仔细看看函数
    将块渲染到字符串()

    第三个参数应该是dict,而不是context。否则它将使用普通上下文实例

    因此,我认为应该是:

    render_block_to_string(template_name, 'ios_message', {},  context)
    

    希望有帮助。

    我可以通过这样做来解决它:

    from django.template.context import make_context
    from django.template.loader import get_template
    
    # Getting the template either by a path or creating the Template object yourself
    template = get_template('your/path/to/the/template.html')
    # Note here the 'template.template' and the 'autoescape=False' parameter
    subject = template.template.render(make_context(context, autoescape=False))
    
    是我自己发现的。因为默认情况下,将从引擎使用自动转义设置


    Django版本:2.2.1

    想发表评论,但由于这是一个新的帐户,我似乎没有足够的声誉

    您可以关闭位于以下位置的
    自动转义

    i、 e


    您能将
    渲染块\u发布到\u string()
    代码吗?它不是本地的Django shortcutWhoops-忘了它不是本地的。添加了链接,而不是粘贴所有90行离线!太棒了,谢谢!真不敢相信我没看到。类似地,我使用了
    render_block_to_string(模板名称,'ios_message',context_instance=context)
    render_block_to_string(template_name, 'ios_message', {},  context)
    
    from django.template.context import make_context
    from django.template.loader import get_template
    
    # Getting the template either by a path or creating the Template object yourself
    template = get_template('your/path/to/the/template.html')
    # Note here the 'template.template' and the 'autoescape=False' parameter
    subject = template.template.render(make_context(context, autoescape=False))
    
    Context(data_dict, autoescape=False)