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''&<>
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/