How to escape special characters in strings and JavaScript code in the Anqi CMS template?
escapeThe filter can escape special characters in a string. For example, it can display HTML code as output instead of parsing the HTML code. As<will be translated to<.escapeIt only escapes five such characters:<,>,&,'and".<will be translated to<,>will be translated to>,&will be translated to&,"will be translated to",'will be translated to'.
Also can be usedeto replaceescape. BecauseeIsescapeAlias, the effect is the same.
By default, all tags are automatically escaped. Therefore, this filter can usually be ignored. It may be needed in some cases.
Also supports using filters, also support usingautoescapeTags to escape the entire block of code.
escapejsThe filter can escape special characters in js code. For example\rwill be translated to\u000D.escapejsWill escape excepta-zA-ZOr space,/Convert all other characters to\uxxxxDisplay format.
Usage method
escapeandeHow to use the filter:
{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}
escapejsHow to use the filter:
{{ obj|escapejs|safe }}
For example, to convert<script>If escaping is needed, it can be written like this:
{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}
# 显示结果
<script>
<script>
UseautoescapeThe tag escapes the entire code block.autoescapeThe tag needs a parameter to clearly specify whether it needs to be escaped or not.onIt is escaped,offIs not escaped.
# 不转义
{% autoescape off %}
{{ "<script>alert('xss');</script>" }}
{% endautoescape %}
# 转义
{% autoescape on %}
{{ "<script>alert('xss');</script>" }}
{% endautoescape %}
# 显示结果
<script>alert('xss');</script>
<script>alert('xss');</script>
Example Demonstration
escapeandeFilter
Directly output the result:
{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}
Display result
<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>
escapejsFilter
{{ "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