In the daily operation of AnQiCMS, the way content is presented and the security are the key factors determining the professionalism and user experience of the website.AnQiCMS is a powerful template engine that draws on many advantages of the Django template engine, and among them, the 'filters' are the unsung heroes behind content formatting and security processing.These filters can help us easily process the output content, whether it is to simplify text, convert formats, or ensure the safety of the content, it becomes accessible.

Filter: Content output of 'Transformers'

In simple terms, a filter is a tool used to convert or process variable values. Its usage in the AnQiCMS template is very intuitive: you add a pipe symbol after a variable.|,Followed by the name of the filter and optional parameters. For example,{{ obj|filter__name:param }}。By flexibly using these filters, we can present the content in the most ideal state on the front-end page。

1. Refine content, optimize reading experience: text truncation and conversion

In website operation, we often need to display a brief description of the article on the list page or in the abstract. If the content is too long, it not only affects the aesthetics but also disperses the user's attention. At this point, AnQiCMS provides various text truncation filters:

  • truncatecharsandtruncatewords:These filters are used to truncate text by character or word count. For example,{{ item.Description|truncatechars:100 }}will truncate the description to a maximum of 100 characters and add “…” at the end.truncatewordsIt is truncated by words.
  • truncatechars_htmlandtruncatewords_html:It is worth noting that if your content contains HTML tags, it will be used directly.truncatecharsIt may destroy the HTML structure. AnQiCMS provides_htmlVersion, they can truncate text while intelligently retaining the complete HTML tags, ensuring that the page structure is not affected, such as{{ articleContent|truncatechars_html:150 }}.
  • Case conversion:upper/lower/capfirst/title
    • upperConvert all English characters to uppercase.
    • lowerConvert all English characters to lowercase.
    • capfirstCapitalize the first letter of a sentence.
    • titleIt will capitalize the first letter of each word, commonly used for title formatting. These filters are very useful when dealing with multilingual content or titles that require specific display styles.
  • String processing:cut/replace/trim/join/split/length
    • cutCan remove specified characters from a string, such as removing extra spaces or special symbols.
    • replaceUsed to replace a substring in a string with another.
    • trim/trimLeft/trimRightIt can effectively remove whitespace from the beginning, end, or both ends of a string, or specify characters.
    • joinandsplitIt is a good helper for converting arrays and strings.joinYou can concatenate array elements into a string with a specified separator, andsplitthen you can split the string into an array with the separator.
    • lengthIt is easy to obtain the length of a string, array, or key-value pair, often used for conditional judgment.
  • Number formatting:floatformat/integer/float
    • floatformatCan accurately control the decimal places of floating-point numbers, for example{{ price|floatformat:2 }}Display the price with two decimal places.
    • integerandfloatIt is used to convert string values to integers or floating-point numbers, which may be necessary before performing mathematical operations.

2. Protect content security: Avoid potential risks

The security of website content is of paramount importance, especially when dynamically loading user-generated content or rich text editor content, the potential XSS (cross-site scripting attack) risk should not be overlooked.AnQiCMS provides multi-layer security mechanisms, the filter being one of them.

  • safeFilter: trust and risk coexistAnQiCMS's template engine defaults to escaping all output content, which means that like<script>This label will be converted to&lt;script&gt;This default mechanism greatly enhances security to prevent the execution of malicious scripts.However, in some cases, such as content generated by rich text editors, we want to display HTML format directly instead of being escaped.This is when it is neededsafeFilter:{{ archiveContent|safe }}.Important reminder:UsesafeThe filter means that you explicitly inform the system that this part of the content is "safe", and does not need to be escaped. Therefore,Be sure to make sure you usesafeThe content source is absolutely credibleOtherwise, it will open the door to XSS attacks.
  • escape/eFilter: Clear escaping intentionAlthough AnQiCMS defaults to automatic escaping,escapeor its abbreviationeThe filter can explicitly express the intention of escaping. It is mainly used in the scenario where automatic escaping is turned off (to force the HTML escaping of specific variables for security purposes){% autoescape off %})
  • escapejsFilter: JS Environment Security GuardianWhen we need to output the content of a variable into JavaScript code,escapejsThe filter is particularly important. It will escape special characters (such as newline characters, quotes, etc.) in strings to make them JS safe and prevent JS syntax errors or injection attacks. For example,var userName = "{{ item.UserName|escapejs }}";.
  • Content cleaning:striptagsandremovetags
    • striptagsCan strip all HTML tags from a string, retaining only plain text content, which is very useful for generating summaries or plain text outputs.
    • removetagsIt is more refined, allowing you to specify the HTML tags to remove, such as{{ content|removetags:"script,iframe" }}You can remove the script and iframe tags from the content, effectively filtering out unnecessary or dangerous elements.

3. Practical auxiliary filter: improve development efficiency

In addition to the aforementioned features, AnQiCMS also includes many practical tools that can greatly enhance the efficiency and robustness of template development and content.

  • Default value handling:defaultanddefault_if_none {{ value|default:"暂无数据" }}:WhenvalueIf the string is empty, zero, false, an empty list, or an empty object, display 'No data available.'.{{ value|default_if_none:"暂无数据" }}It is only when:valueWithnilWhen a null pointer is encountered, the default value is displayed. For empty strings, zeros, and others, they are retained. These two filters are very useful for ensuring the integrity of page data.
  • URL-related filters:urlize/urlizetrunc/urlencode/iriencode
    • urlizeAutomatically recognizes URLs and email addresses in text, and converts them into clickable hyperlinks, and automatically addsrel="nofollow"Very suitable for handling users