How do `filters` (such as `truncatechars`, `safe`) format or sanitize the output content?

Calendar 👁️ 67

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

Related articles

How `include`, `extends`, and `macro` tags enhance the reusability and maintainability of template code?

## Improving AnQi CMS template efficiency and maintainability: the clever use of `include`, `extends`, and `macro` In the daily content operation of AnQi CMS, we often need to create and manage a large number of pages.How to ensure that these pages maintain consistency while also being developed and maintained efficiently is a challenge that every operator has to face.

2025-11-08

How to use the `stampToDate` tag to format a database timestamp into a readable date?

In website operation, we often encounter such situations: the time information stored in the database, such as the publication time of articles, the creation time of goods, etc., is often in the form of a series of numbers (timestamps).This string of numbers is clear to machines, but it has poor readability for us users.Imagine, if next to an article it displays '1678886400' instead of '2023/03/15', wouldn't that be a big discount in experience?AnQi CMS knows this and has provided a very practical template tag——`stampToDate`

2025-11-08

How to flexibly control the conditional display and loop iteration of logic tags such as `if` and `for` in the template?

In the world of AnQi CMS templates, we often need to display content based on different conditions or repeat a series of data, at this point, the `if` and `for` logical tags become particularly important.They are the foundation for building dynamic content and implementing flexible layouts in templates, allowing us to precisely control the presentation of every piece of information on the web page.

2025-11-08

How to use the `pagination` tag to generate a beautiful pagination navigation for articles or product lists?

In website operation, as the content volume continues to grow, whether it is articles, products, or other lists, how to efficiently organize and display these contents while ensuring a smooth user browsing experience and a friendly search engine is a problem that needs to be carefully considered.Page navigation is the key tool to solve this problem.AnQiCMS provides a powerful and flexible `pagination` tag that allows you to easily create beautiful and functional pagination navigation for various lists.

2025-11-08

How to render Markdown editor content correctly on the front-end page?

In AnQiCMS, Markdown is an efficient and widely popular content creation method.It uses a concise markup syntax, allowing creators to focus on the content itself without being troubled by complex layout tools.However, to present these concise Markdown texts to the user in the browser, it requires the collaborative processing of the AnQiCMS backend and the frontend template.Understanding this process can help you better utilize the content management capabilities of AnQiCMS, ensuring that your content is displayed in **status**.### Enable

2025-11-08

How to correctly display mathematical formulas and flowcharts in Markdown content?

With the popularity of the built-in Markdown editor of AnQiCMS, many users hope to be able to display information more flexibly in their website content, especially for technical documents, tutorials, or data analysis, the presentation of mathematical formulas and flowcharts has become particularly important.AnQiCMS integrates external libraries to bring powerful extension capabilities to Markdown content, making it easy and convenient to display professional content.

2025-11-08

How does the 'recommended attribute' of a document affect the call and display priority of content on the front end when it is published?

When using Anq CMS to manage website content, we often need to highlight certain important articles or products to make them easier for visitors to find.This is when the "recommended attribute" of content publishing comes into play.It is not a complex backend setting, but rather a very intuitive option that can be seen on the 'Add Document' interface every time we publish or edit a document. It is an important tool for effectively managing content display and call priority.

2025-11-08

How to optimize search engine crawling and user experience with static rules (such as URL structure)?

In website operation, the URL plays a vital role.A well-designed URL can not only help search engines better understand and crawl the website content, but also significantly improve the user experience.AnQiCMS (AnQiCMS) understands this point, therefore, it has integrated flexible and powerful pseudo-static rules and 301 redirect management functions into its system, allowing website administrators to easily build URL structures that are friendly to both search engines and users. ### Static rules: Why are they so important?Imagine that

2025-11-08