Escape special characters in a string or JavaScript code

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 output HTML code as is, instead of parsing the HTML code.<will be converted to&lt;.escapeIt escapes only five such characters:<,>,&,'And".<will be converted to&lt;,>will be converted to&gt;,&will be converted to&amp;,"will be converted to&quot;,'will be converted to&#39;.

It can also be usedeinstead.escapeBecause.eYesescapeIt 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 usingautoescapetags to escape entire blocks of code.

escapejsFilters can escape special characters in js code. For example,\rwill be converted to\u000D.escapejsit will escapea-zA-Zor spaces,/All other characters outside of quotes should be converted to\uxxxxThe displayed form.

Usage Instructions

escapeAndeHow to use the filter:

{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}

escapejsHow 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 }}
# 显示结果
&lt;script&gt;
&lt;script&gt;

Useautoescapetags to escape the entire code block.autoescapeThe label needs a parameter to specify whether it should be escaped or not.onIt is escaped.offIt is not escaped.

# 不转义
{% autoescape off %}
{{ "<script>alert('xss');</script>" }}
{% endautoescape %}
# 转义
{% autoescape on %}
{{ "<script>alert('xss');</script>" }}
{% endautoescape %}
# 显示结果
<script>alert('xss');</script>
&lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt;

Here is an example demonstration

escapeAndeFilter

Directly output the result:

{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}

Display results

&lt;script&gt;
&lt;script&gt;

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:

&lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt;
<script>alert('xss');</script>
&lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt;
&lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt;

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