How filters (such as `truncatechars`, `safe`, `floatformat`) handle and format the data to be displayed?

Calendar 👁️ 70

In Anqi CMS template design, filters play a crucial role, they are like the 'beautician' and 'processor' of data, able to process and format the original data to be displayed in the template, making it more beautiful and more in line with the needs of visitors.Understand and make good use of these filters, which can make your website content more flexible and professional.

The template syntax of AnQi CMS has borrowed from Django template engine, therefore the usage of filters is also very intuitive: usually, variables are connected with filters using the pipe symbol|Connect, if the filter requires parameters, then add a colon after the filter name:with parameters. For example,{{ 您的变量 | 过滤器名称 : 参数 }}.

Next, we will delve into several commonly used filters to understand how they help us process and format data.

The tool for processing text length:truncatechars

When you display the article summary on the list page, or need to show a long text in a limited space, truncatecharsThe filter will be your helpful assistant. It can truncate strings to the specified character count and automatically add an ellipsis (...), making the content concise and guiding.

For example, if you have a long article title or abstract{{ article.Description }}You want it to display a maximum of 50 characters. Just use it like this:{{ article.Description | truncatechars:50 }}.

If you prefer to truncate by word count rather than character count, thentruncatewordsThe filter can also meet the requirements. What's more, AnQi CMS also provides a truncation method that is friendly to HTML content:truncatechars_htmlandtruncatewords_html.This means that even if your content contains HTML tags, they can be smartly preserved during truncation, avoiding layout chaos, which is particularly useful when dealing with rich text editor output.

The key to safely displaying content:safe

In the template rendering mechanism of Anqi CMS, for security reasons, all data output from the background to the front-end is automatically escaped as HTML by default. This means that things like<script>Such HTML tags will be converted to&lt;script&gt;To prevent malicious code injection (XSS attack). This is a good protection mechanism in most cases.

However, sometimes, the content we need to display itself contains valid HTML code, such as the text and graphic content edited by a rich text editor on the article detail page, or certain special formatted layouts.At this time, if the content is escaped, it will be displayed as the original HTML code instead of the rendered effect.safeThe filter comes into play.

You can use it to{{ article.Content | safe }}Render rich text content safely to the page in HTML format. But please note that, usingsafeMeans you trust the source of the content, ensure it does not contain any potential malicious scripts, otherwise it may pose a security risk.Therefore, use this filter only when you are sure that the content is safe.

An assistant for presenting precise numbers:floatformat

When displaying prices, ratings, or any numbers with decimals,floatformatThe filter can help you present these numbers in a uniform and professional format.

The most common use is to control the decimal places of floating-point numbers. For example, if you have a product price{{ product.Price }}Is34.23234, you may want it to be displayed as34.23. Use{{ product.Price | floatformat:2 }}you can achieve it.

floatformatThe default behavior is to keep one decimal place and remove the extra zeros after the decimal point (for example34.000It will be displayed as34,34.200It will be displayed as34.2). If you specify the number of decimal places (such as:2),Even zero will be preserved to ensure the consistency of the display format (for example34.000It will be displayed as34.00)。It even supports negative numbers as parameters, used to round from the end of the number. This makes the display of numbers more flexible and precise.

More members of the filter family.

In addition to the several commonly used filters mentioned above, Anqi CMS also provides a wealth of filters to meet various data processing needs:

  • Text processing: such aslower(Convert to lowercase),upper(Convert to uppercase),title(Word With Capital Letter,)cut(Remove Specified Character,)replace(Replace String) and so on, keep your text content standardized and consistent.
  • Date and Time: AlthoughstampToDateis a commonly used label function, but combineddateFiltering processtime.Timetype of variables, or in some advanced scenarios, filters can provide more detailed time formatting.
  • Data structure:lengthCan get the length of a string, array, or object (map),joinCan concatenate array elements into a string with a specified separator,splitThen you can split the string into an array by the separator.
  • URL and escaping:urlencodeURL parameters encoding,urlizeWill automatically recognize links in text and convert them to clickable hyperlinks.

These filters collectively constitute the powerful and flexible template system of AnQi CMS, allowing you to easily master various content display requirements and create a professional and user-friendly website interface.


Frequently Asked Questions (FAQ)

1. Can multiple filters be applied to a variable at the same time? What is the order of execution?Yes, you can chain multiple filters to apply to a variable.The execution order is from left to right, the output of the previous filter will be the input of the next filter.{{ content | truncatechars:100 | safe }}The content will be truncated to 100 characters (including HTML tags), and then the truncated content will be output as safe HTML.

2. What will happen if the filter receives data of a type that does not meet the requirements?In most cases, the filter of Anqi CMS tries to intelligently handle different types of data.If the data type is incompatible, the filter will usually ignore the operation and return the original data, or return an empty value, rather than cause the page to error directly.floatformatIt may return the original string or null value. However, in actual development, it is still recommended to ensure that the data type is consistent with the filter's expectations to obtain the most accurate results.

3. In addition to those mentioned in the article, what are some common filters that can help me process data?AnQi CMS provides a variety of filters to process different types of data. In addition to text truncation, safe output, and floating-point formatting, you can also useadd(Addition of numbers or strings),cut(Remove Specified Character,)lower/upper(Case conversion),date(Date formatting),length(Get length),join/split(Conversion between string and array) as well}urlize(Automatically identify and link URLs) etc. These filters are detailed in the "More Filters" document of the template, and it is recommended that you consult the official documentation for more information.

Related articles

How to manage and display document tags and associated document lists for `tagList` and `tagDataList` tags?

In content management, tags are an important bridge for connecting content, enhancing user experience, and optimizing search engine performance.AnQi CMS understands its importance, providing powerful tag management functions, and through the two core tags `tagList` and `tagDataList`, allowing content operators to flexibly display and manage document tags and their associated content. ### Tag: A Tool for Content Categorization and Discovery Tags in Anqi CMS are not just simple keywords; they are a refined way of organizing content.

2025-11-07

How does the `pagination` tag handle the pagination display logic for article lists and product lists?

How to efficiently display a large number of articles or products in a content management system without sacrificing user experience, this is often a challenge faced by website operators.AnQiCMS (AnQiCMS) provides powerful template tag features, among which the `pagination` tag is a powerful tool to solve this problem, allowing flexible handling of pagination logic for article lists and product lists, making your website content well-organized.

2025-11-07

How `prevArchive` and `nextArchive` tags display the link and title of the previous/next document?

When browsing website content, users often hope to be able to easily jump from the current page to related or adjacent articles.This kind of previous/next navigation can not only significantly improve user experience, but also play an active role in SEO, guiding search engine spiders to more deeply crawl website content.

2025-11-07

How to generate breadcrumb navigation using the `breadcrumb` tag to enhance the user's understanding of the page hierarchy?

In complex website content structures, users sometimes feel lost, not knowing the position of the current page.At this time, an auxiliary navigation method called "Breadcrumb Navigation" is particularly important.It not only clearly displays the path from the home page to the current page, but also helps users quickly understand the hierarchical structure of the website, thereby improving the browsing experience.For websites built with AnQiCMS, the system-built `breadcrumb` tag is exactly the tool to generate this efficient navigation.

2025-11-07

How can AnQi CMS efficiently display and manage content from multiple sites on a single interface?

## AnQi CMS: The Secret to Mastering Multi-site Content on a Single Interface In the digital wave, many enterprises or individuals often have more than one website to meet different business or content publishing needs, such as brand official websites, product display pages, sub-sites, marketing activity pages, or independent sites for users in different regions or languages.However, managing and operating the content of multiple websites often becomes a huge challenge due to its complexity, repetitive workload, and the difficulty of resource integration.How to achieve the centralized display and management of these scattered contents on a unified platform

2025-11-07

How to utilize the flexible content model of Anqi CMS to create unique display methods for different types of content?

In today's increasingly important era of content marketing, the way a website presents its content directly affects user experience and the efficiency of information communication.A powerful and flexible content management system (CMS) can help us easily meet a variety of content display needs.AnQiCMS (AnQiCMS) leverages its excellent 'flexible content model' feature, providing endless possibilities for customized display of various content.This article will delve into how to cleverly utilize this core feature to create a unique presentation for your website content.Understanding AnQi CMS's flexible content model

2025-11-07

How does AnQi CMS support seamless switching and accurate display of multilingual content?

Today, with the increasing trend of globalization, companies and content creators have a growing demand for building multilingual websites.A CMS that can seamlessly switch and accurately display content, not only can it effectively expand the international market, but it can also significantly improve the user experience.AnQiCMS (AnQiCMS) provides a flexible and efficient solution in multilingual support, helping users easily cope with the challenges of global content operations.The Anqi CMS implements multilingual functionality based on its powerful multi-site management foundation.

2025-11-07

How to configure the AnQi CMS pseudo-static URL to optimize the search engine friendly display of website content?

In website operation, making the web page address (URL) friendly to search engines is a crucial step.A clear and meaningful URL not only helps users quickly understand the page content, but is also an important indicator for search engines to evaluate the quality and relevance of the content.AnQiCMS fully understands this point, therefore, from the very beginning of system design, it has fully considered the needs of pseudo-static, and provided an intuitive and convenient configuration method, so that your website content can be presented in the most favorable form for search engine crawling and understanding.### Understanding the value of pseudo-static and its impact on SEO First

2025-11-07