How to escape special characters such as HTML code in Anqi CMS templates such as strings and js code?
escape
Filters can escape special characters in strings. For example, output HTML code to display instead of parsing HTML code. like<
Will be converted to<
.escape
It only escapes five such characters:<
,>
,&
,'
and"
.<
Will be converted to<
,>
Will be converted to>
,&
Will be converted to&
,"
Will be converted to"
,'
Will be converted to'
.
Can also be usede
Let's replaceescape
. becausee
yesescape
The alias of , the use effect is consistent.
By default, all tag outputs are automatically escaped. Therefore, this filter can be ignored in general. In some cases, it may be necessary.
In addition to using filters, it also supportsautoescape
The tag escapes the entire code.
escapejs
Filters can escape special characters in js code. like\r
Will be converted to\u000D
.escapejs
Will be aparta-zA-Z
or space,/
Other characters other than\uxxxx
display form.
How to use
escape
ande
How to use filters:
{{ "<script>"|safe|escape }} {{ "<script>"|safe|e }}
escapejs
How to use filters:
{{ obj|escapejs|safe }}
For example<script>
Escape, you can write this:
{{ "<script>"|safe|e }} {{ "<script>"|safe|e }} # Show results <script> <script>
useautoescape
The tag escapes the entire code.autoescape
The tag needs a parameter to clearly state whether it is necessary to escape or not.on
It's escape,off
It is not escaped.
# 不转义 {% autoescape off %} {{ "<script>alert('xss');</script>" }} {% endautoescape %} # 转义 {% autoescape on %} {{ "<script>alert('xss');</script>" }} {% endautoescape %} # 显示结果 <script>alert('xss');</script> <script>alert('xss');</script>
Sample Demo
escape
ande
Filter
Direct output result:
{{ "<script>"|safe|escape }} {{ "<script>"|safe|e }}
Show results
<script> <script>
useautoescape
{{ "<script>alert('xss');</script>" }} {% autoescape off %} {{ "<script>alert('xss');</script>" }} {% endautoescape %} {% autoescape on %} {{ "<script>alert('xss');</script>" }} {% endautoescape %} {% autoescape off %} {{ "<script>alert('xss');</script>"|escape }} {% endautoescape %}
输出结果:
<script>alert('xss');</script> <script>alert('xss');</script> <script>alert('xss');</script> <script>alert('xss');</script>
escapejs
Filter
{{ "escape sequences \r\n\'\" special chars "?!=$<>"|escapejs|safe }} # 显示结果 escape sequences \u000D\u000A\u005C\u0027\u005C\u0022 special chars \u0022\u003F\u0021\u003D\u0024\u003C\u003E