How to prevent auto escape in Django templates?

孤街醉人 提交于 2019-11-29 02:47:49

问题


In the docs it says:

The only exceptions are variables that are already marked as “safe” from escaping, either by the code that populated the variable, or because it has had the safe or escape filters applied."

How does the "populated the variable" part work ? I'm actually looking for a way to declare a template tag as safe in the view. I somehow think it's not a good idea to let a designer decide. My co-worker will just add it whenever she 'thinks' it's a good idea.

https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs


回答1:


Django has a subclass of strings called safe strings (specifically SafeUnicode or SafeString), which can be created using django.utils.safestring.mark_safe. When the template engine comes across a safe string it doesn't perform HTML escaping on it:

>>> from django.utils.safestring import mark_safe
>>> from django.template import Template, Context
>>> Template("{{ name }}").render(Context({'name': mark_safe('<b>Brad</b>')}))
u"<b>Brad</b>"

If you're writing your own template tag, you need to implement render() which will return a string that will be treated as safe, meaning you have to handle any escaping necessary yourself. However if you're writing a template filter, you can set the attribute is_safe = True on the filter to avoid auto escaping of the returned value, e.g.

@register.filter
def myfilter(value):
    return value
myfilter.is_safe = True

See https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping for details.




回答2:


You could call django.utils.safestring.mark_safe and pass you variable

...
return direct_to_template('my-template.html', {'safe_var': mark_safe('<script>alert("");</script>')})

In template it will be printed without escaping (alert will popup). Though auto-escape is really a great feature that will save you from some bad things.



来源:https://stackoverflow.com/questions/8774902/how-to-prevent-auto-escape-in-django-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!