django - 如何从 View 中禁用 Django 的自动转义?

标签 django django-templates escaping

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

  • 使用 |safe在变量
  • 之后
  • 使用 {% autoescape on %}{% endautoescape %}块内
  • 使用类似 context = Context({'message': message}, autoescape=False) 的上下文

  • (1) 和 (2) 工作正常。但是我有这样的情况,我有模板来生成纯文本推送通知,而且我有大量的模板需要构建和维护。我可以通过并输入 {% autoescape on %}{% endautoescape %}标签,但 (3) 应该允许我在 View 中的一行中完成。

    模板:
    {% block ios_message %}{{message}}{% endblock %}
    

    风景:
    message = u"'&<>"
    context = Context({'message': message}, autoescape=False)
    render_block_to_string(template_name, 'ios_message', context)
    

    输出:
    u'&#39;&amp;&lt;&gt;
    

    block_render.py 的代码来自这里:https://github.com/uniphil/Django-Block-Render/blob/master/block_render.py .我从那里按原样使用它。

    有谁知道是什么给的?

    最佳答案

    仔细看看函数 render_block_to_string() :

    def render_block_to_string(template_name, block, dictionary=None,
                               context_instance=None):
        """Return a string
    
        Loads the given template_name and renders the given block with the
        given dictionary as context.
    
        """
        dictionary = dictionary or {}
        t = _get_template(template_name)
        if context_instance:
            context_instance.update(dictionary)
        else:
            context_instance = Context(dictionary)
        return render_template_block(t, block, context_instance)
    

    第三个参数应该是一个字典,而不是上下文。否则它将使用正常的上下文实例。

    所以我认为应该是:
    render_block_to_string(template_name, 'ios_message', {},  context)
    

    希望能帮助到你。

    关于django - 如何从 View 中禁用 Django 的自动转义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18211286/

    相关文章:

    django - DEBUG=False 时无法访问管理面板中的模型

    python - 使用用户定义的主键 Django 更新数据库中的元素

    django - 媒体文件中的图像不会显示在 django 模板中

    django InlineFormsets 错误报告,表单集错误列表为空

    postgresql - SQL 中有转义变量的机制吗?

    django - 如果MEDIA_URL在STATIC_URL内,则runserver无法提供媒体

    javascript - Django 模板变量和 Javascript

    python - "\b"字符串中行为不当

    bash - Bash 中的回显 : Escape Apostrophes?

    python - 如何在django中删除项目