Django模板转义 [英] Django template escaping
问题描述
Django模板系统为html中的内容提供了一些选项(过滤器),但是对于初学者来说,这是一种令我困惑的事情。说我正在跟随一个教程来制作一个简单的博客,并且博客内容需要被转义 - 我相信内容,因为我是唯一编辑它的内容。所以问题是我应该像 {{post.content | autoescape}}
, {{post.content | escape}}
或 {{post.content | safe}}
在html?
谢谢
编辑:我应该使用哪个过滤器自动将特殊字符转换为html实体?
编辑2:我只是意识到autoescape不是有效的过滤器。
默认情况下,Django模板中的HTML转义已打开。
Autoescape是一个标签。不是过滤器:
{%autoescape on%}
{{post.content}}
{ %endautoescape%}
转义过滤器转义字符串的HTML。具体来说,它会进行这些替换:
- <被转换为
& lt;
- >被转换为
& gt;
- '(单引号)转换为
&#39;
- &转换为
& amp ;
< (双引号)转换为
& quot;
除了几个角落外,'force_escape'几乎与escape相同。 / p>
安全过滤器会将您的内容标记为安全,因此不会被转义(将按照原样发送到浏览器)。
我应该使用哪个过滤器将特殊字符自动转换为html实体?
嗯,你的意思是像转换Ã
到& Atilde;
?坚持使用utf-8编码全部方式并忘记那些。
Django templating system provides a few options (filters) for escaping contents in the html, but they are kind of confusing to me as a beginner. Say I'm following a tutorial to make a simple blog, and the blog content needs to be escaped - I trust the content because I am the only one editing it. So the question is should I do it like {{ post.content|autoescape }}
, {{ post.content|escape }}
, or {{ post.content|safe }}
in the html?
Thanks
EDIT: Which filter should I use to have special characters converted to html entities automatically?
EDIT 2: I just realized that autoescape is not a valid filter.
HTML escaping is on by default in Django templates.
Autoescape is a tag. not a filter:
{% autoescape on %}
{{ post.content }}
{% endautoescape %}
The 'escape' filter escapes a string's HTML. Specifically, it makes these replacements:
- < is converted to
<
- > is converted to
>
- ' (single quote) is converted to
'
- " (double quote) is converted to
"
- & is converted to
&
The 'force_escape' is almost identical to 'escape' except for a few corner cases.
The 'safe' filter will mark your content as safe, so it won't be escaped (will be sent to browser as is).
Which filter should I use to have special characters converted to html entities automatically?
Well, you mean, like converting Ã
to Ã
? Stick with utf-8 encoding all the way and forget about those.
这篇关于Django模板转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!