How to escape special characters in strings and JavaScript code in the AnQi CMS template?
escape
The filter can escape special characters in a string. For example, it can output HTML code as is, instead of parsing the HTML code.<
will be converted to<
.escape
It escapes only five such characters:<
,>
,&
,'
And"
.<
will be converted to<
,>
will be converted to>
,&
will be converted to&
,"
will be converted to"
,'
will be converted to'
.
It can also be usede
instead.escape
Because.e
Yesescape
It has the same effect as the alias.
By default, all tag outputs are automatically escaped. Therefore, this filter can generally be ignored. It may be needed in certain situations.
In addition to using filters, it also supports usingautoescape
tags to escape entire blocks of code.
escapejs
Filters can escape special characters in js code. For example,\r
will be converted to\u000D
.escapejs
it will escapea-zA-Z
or spaces,/
All other characters outside of quotes should be converted to\uxxxx
The displayed form.
Usage Instructions
escape
Ande
How to use the filter:
{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}
escapejs
How to use the filter:
{{ obj|escapejs|safe }}
For example, to transform<script>
If escaping is used, it can be written like this:
{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}
# 显示结果
<script>
<script>
Useautoescape
tags to escape the entire code block.autoescape
The label needs a parameter to specify whether it should be escaped or not.on
It is escaped.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>
Here is an example demonstration
escape
Ande
Filter
Directly output the result:
{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}
Display 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 %}
Output result:
<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