【问题标题】:How do I disable Django's autoescape from a view?如何从视图中禁用 Django 的自动转义?
【发布时间】:2013-08-15 04:46:06
【问题描述】:

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

  1. 在变量后使用|safe
  2. 在块内使用{% autoescape on %}{% endautoescape %}
  3. 使用像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)

输出:

u'&#39;&amp;&lt;&gt;

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

有谁知道是什么给的?

【问题讨论】:

  • 您能发布render_block_to_string() 代码吗?这不是原生的 Django 快捷方式
  • 哎呀 - 忘了它不是原生的。已添加 in 链接而不是粘贴所有 90 行!

标签: django django-templates escaping


【解决方案1】:

仔细查看函数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)

希望对你有帮助。

【讨论】:

  • 太棒了,谢谢!不敢相信我没有看到。同样,我使用了render_block_to_string(template_name, 'ios_message', context_instance=context)
【解决方案2】:

我可以这样解决它:

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))

我自己做的。因为默认情况下,引擎会使用自动转义设置 https://github.com/django/django/blob/4b6dfe16226a81fea464ac5f77942f4d6ba266e8/django/template/backends/django.py#L58-L63

Django 版本:2.2.1

【讨论】:

    【解决方案3】:

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

    您可以关闭此处的autoescapehttps://github.com/django/django/blob/529c3f264d99fff0129cb6afbe4be2eb11d8a501/django/template/context.py#L137

    Context(data_dict, autoescape=False)
    

    【讨论】:

      猜你喜欢
      • 2010-12-08
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      相关资源
      最近更新 更多