In website content operation, the way content is displayed and the security are equally important. Anqi CMS, as an efficient content management system, provides comprehensive considerations for website security, among whichescapeandescapejsFilters are important tools for us to combat network attacks and ensure that content is displayed correctly. Understanding their functions can help us better manage and publish content.

The first line of defense in website security: XSS attacks and content escaping

Imagine if your website allows users to submit comments or publish articles, and this content contains some malicious code (such as...<script>alert('您被攻击了!')</script>

To prevent such attacks, any content received from users that may be displayed on the page should be 'sanitized' or 'escaped'. The purpose of escaping is to convert special characters (such as</>/'/"Convert them to their corresponding HTML entities (such as&lt;/&gt;), so that the browser will not recognize them as code but display them as plain text.

Safe CMS has already considered this point when processing template output.This means that most of the variables you output directly in the template will be automatically escaped by the system.This is a very important security feature that provides basic protection for the website without you noticing.

escapeandeFilter: Explicitly perform HTML escaping

Although AnQi CMS defaults to HTML escaping, there may be times when we want to explicitly indicate that a variable needs to be escaped, or that manual control of escaping behavior is required in certain special scenarios. At this point,escapeThe filter comes into play.

escapeThe filter's role is to convert five specific characters in a string:</>/&/'and"to their corresponding HTML entities. For example,<script>It will be converted into&lt;script&gt;. Its alias ise, which is more concise to use.

Example of Use Case:

Suppose there is a variable containing HTML code in your background article contentmyHtmlContentIf you want this HTML code to be displayed as plain text rather than being parsed by the browser, you can useescape:

<p>这是原文内容:{{ myHtmlContent }}</p>
<p>经过转义后显示为:{{ myHtmlContent|escape }}</p>

In most cases, due to the automatic escaping mechanism of Anqi CMS,{{ myHtmlContent }}and{{ myHtmlContent|escape }}there may be no difference in the final HTML output. But explicitly usingescapeCan enhance the readability of the code, clearly express your intentions, and prevent unexpected behaviors that may occur in some extreme or complex nested template scenarios.

safeFilter: Allow trusted HTML content

Of course, not all HTML code needs to be escaped. For example, if you use a rich text editor for users to create content, this content will usually contain valid HTML tags such as<strong>/<p>/<img>In order to make the content more rich in style. If this content is also escaped, then the carefully formatted effect of the user will be lost, and only plain text will remain.

At this point, we need to inform Anqi CMS: 'This content is trusted, the contained HTML is valid, please parse and display it directly without escaping.' This issafethe function of the filter.

Example of Use Case:

Assuming your article detail page needs to display content generated by a rich text editorarchive.ContentThis content includes various HTML tags:

<div class="article-content">
    {{ archive.Content|safe }}
</div>

Important reminder:safeThe filter will bring security risks!

Once usedsafeYou explicitly tell AnQiCMS: This content is safe and does not require escaping. This means that the responsibility for the content's safety is entrusted to you. Therefore,Only when you are one hundred percent sure that the content source is reliable, strictly reviewed, and does not contain malicious code, should you use it.safefilter.Absolutely do not pass user input未经审核 directly.|safeOutput, otherwise your website will face a huge risk of XSS attacks.

escapejsFilter: Safeguarding JavaScript code.

In addition to the HTML context, we sometimes need to embed dynamic data in JavaScript code. For example, you might need to assign the value of a backend variable to a JavaScript variable, or inalert()A message is displayed in the function.JavaScript has its own set of special character handling rules, and inserting a string containing special characters directly into JavaScript code can also lead to syntax errors or security vulnerabilities.

escapejsThe filter is designed for this purpose. Its function is to convert special characters in a string (including newline characters, single and double quotes, backslashes, etc.) into safe JavaScript string literals\uxxxxForm. So, the escaped string can be safely embedded in JavaScript code.

Example of Use Case:

Suppose you want to use JavaScript'salertA pop-up displays a user inputuserNamewhileuserNameMay contain single quotes or newlines:

<script>
    var user = '{{ userName|escapejs }}';
    alert('欢迎,' + user + '!');
</script>

If notescapejsifuserNamehas a value ofO'ReillyJavaScript code will becomevar user = 'O'Reilly';Causing syntax errors. Withescapejsit will becomevar user = 'O\u0027Reilly';Ensured the correctness and security of the code.

escapejswithescapeThe difference is:

escapeFor safe display in the HTML context, whileescapejsIt is for the safe use in JavaScript context.They handle special characters and escape sequences differently, be sure to choose the correct filter according to the context in which the content ultimately appears.

autoescapeTag: Flexible control of the escaping rules of code blocks

Except for using filters for individual variables, Anqicms also providesautoescapetags to allow you to control the automatic escaping behavior within a code block.

autoescapetags that can acceptonoroffAs a parameter. When set tooff, all variable outputs within the tag will no longer be automatically HTML-escaped unless you explicitly use|escapeor|escapejs. When set toonWhen the default automatic escaping is globally turned off, the content within this block will be forcibly escaped.

Example of Use Case:

Assuming you have a template snippet, most of which is reviewed and safe HTML, you do not want to use it frequently|safe:

{% autoescape off %}
    <div class="header-banner">
        {{ trustedBannerHtml }}
    </div>
    <p>以下内容是用户提交的,需要注意安全:{{ userInputText|escape }}</p>
    <script>
        var message = '{{ dynamicMessage|escapejs }}';
    </script>
{% endautoescape %}

In this example,trustedBannerHtmlbecause inautoescape offtags it is not escaped. AnduserInputTextalthough inoffWithin the block, but we still explicitly used|escapeto ensure its security,dynamicMessagethen use|escapejsto ensure safety in JavaScript.

Summary

Anq CMS has made many efforts in terms of website security, among whichescape/escapejsandsafeas well as filtersautoescapeTags are an indispensable tool in template development and content operations.

  • Default automatic escapingIs basic security protection.
  • escape(ore) is used to convert special characters to HTML entities, ensuring the pure text display of HTML content.
  • safeused fortrust and allow passageParsing of valid HTML code, but it must be used with caution as it is one of the main sources of security risks.
  • escapejsUsed to safely embed data into JavaScript code, preventing script injection and syntax errors.
  • autoescapeTags provide a flexible way to control escaping behavior within a template scope.

Using these tools reasonably and cautiously will help you build a website that is both beautiful and secure.


Frequently Asked Questions (FAQ)

1. Why is the HTML tag in my article content displayed as code instead of rendering effects on the front end?

This is usually because of the Anqi CMS.