Escape special characters in strings and js code

How to escape special characters such as HTML code in strings and JavaScript code in the Anqi CMS template?

escapeThe filter can escape special characters in strings. For example, it can output HTML code for display instead of parsing the HTML code. As<Will be converted to&lt;.escapeIt only escapes 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;.

Can also be usedeLet's replaceescape. becauseeyesescapeThe 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 supportsautoescapeThe tag escapes the entire code.

escapejsThe filter can escape special characters in JavaScript code. For example,\rWill be converted to\u000D.escapejsWill be aparta-zA-Zor space,/Other characters other than\uxxxxdisplay form.

How to use

escapeandeHow to use filters:

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

escapejsHow to use filters:

{{ obj|escapejs|safe }}

For example<script>Escape, you can write this:

{{ "<script>"|safe|escape }}
{{ "<script>"|safe|e }}
# 显示结果
&lt;script&gt;
&lt;script&gt;

useautoescapeThe tag escapes the entire code.autoescapeThe tag needs a parameter to clearly state whether it is necessary to escape or not.onIt's escape,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;

Sample Demo

escapeandeFilter

Direct output result:

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

Show 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 %}

输出结果:

&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