Escape special characters in strings and js code

How to escape special characters such as HTML code in Anqi CMS templates such as strings and js code?

escapeFilters can escape special characters in strings. For example, output HTML code to display instead of parsing HTML code. like<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.

escapejsFilters can escape special characters in js code. like\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|e }}
{{ "<script>"|safe|e }}
# Show results
<script>
<script>

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>
<script>alert('xss');</script>

Sample Demo

escapeandeFilter

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>

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