awi*_*ery 5 django escaping django-templates
Django 说有 3 种方法可以关闭自动转义:
|safe在变量之后使用{% autoescape on %}and{% endautoescape %}context = Context({'message': message}, autoescape=False)(1)和(2)工作正常。但我遇到的情况是,我有模板来生成纯文本推送通知,并且我有大量模板需要构建和维护。我可以遍历所有内容并将{% autoescape on %}和{% endautoescape %}标签放入其中,但是 (3) 应该允许我在视图中的一行中完成此操作。
模板:
{% block ios_message %}{{message}}{% endblock %}
Run Code Online (Sandbox Code Playgroud)
风景:
message = u"'&<>"
context = Context({'message': message}, autoescape=False)
render_block_to_string(template_name, 'ios_message', context)
Run Code Online (Sandbox Code Playgroud)
输出:
u''&<>
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
第三个参数应该是一个字典,而不是上下文。否则它将使用普通的上下文实例。
所以我认为应该是:
render_block_to_string(template_name, 'ios_message', {}, context)
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
5281 次 |
| 最近记录: |