How to process front-end displayed data twice through the `filter` filter, such as truncating characters or formatting?

Calendar 👁️ 64

In AnQi CMS, data is stored in its original form, but we know that the data displayed on the front end needs to be carefully crafted to present in a**posture**to the user. At this time, the "filter" in the template engine is the one thatfilterIt has become an indispensable tool in our hands.It can process data twice, whether it is to accurately截取long text, unify date format, or cleverly handle HTML content, it can easily cope with it, making your website content both professional and attractive.

Understand the core function of the "filter".

Imagine when data is extracted from a database, it's like uncut jade.And the filter, like a master craftsman, goes through a series of processes to polish these rough stones into shining treasures.In Anqi CMS template syntax, the use of filters is very intuitive.|Pass data (or variables) to the filter, and if the filter requires additional configuration, it can be done through the colon.:Add parameters. The basic form is usually:{{变量名 | 过滤器名称 : 参数}}.

This design makes the data processing logic clearly separated from the content display logic, making the template code cleaner, and also easier to maintain and understand.Let's delve deeper into the powerful functions of some commonly used filters.

Precisely control text: slicing, formatting and cleaning

Website content, especially dynamically generated content, often needs to be controlled for text length according to layout requirements or standardized formatting.

Character and word truncation

When we want to display the article summary on the list page and do not want the summary to be too long,truncatecharsandtruncatewordsit comes in handy.truncatecharsIt will be truncated according to the set character count, even if it cuts off in the middle of a word, and an ellipsis will be added at the end....HowevertruncatewordsIt will intelligently split by words, ensuring that no half-word appears, just like...The end. If the content contains HTML tags, to avoid destroying the page structure, we can also use their corresponding HTML safe versions: truncatechars_htmlandtruncatewords_html.

For example, if you want to display the first 50 characters of an article:{{ article.Description | truncatechars:50 }}

Case conversion and title beautification

To maintain the consistency of the website style, we sometimes need to unify the case of the text.upperCan convert all English letters to uppercase,lowerThen convert to lowercase. If you need to capitalize the first letter of a sentence, you can usecapfirstHowevertitleThe filter is more suitable for processing titles, it will capitalize the first letter of each word and keep the rest in lowercase, making the title look more standardized.

For example, uniform the format of the title to the first letter of each word in uppercase:{{ article.Title | title }}

Remove redundant characters and spaces

Sometimes, data imported from external sources may contain unnecessary spaces or specific characters.trimThe filter can remove whitespace characters from the beginning and end of a string. If you need to remove specific characters,trim/trimLeft(delete from the left) andtrimRight(Delete to the right) Both can accept a parameter to specify the character set to be deleted.cutThe filter is more direct, it will remove all the matched specific substrings in the string.

For example, remove whitespace from both ends of the text:{{ " 安企CMS很棒 " | trim }}

Handling multi-line text with line breaks

When displaying long text with line breaks entered from the editor, we usually want these line breaks to be rendered correctly as HTML line breaks.<br/>Or paragraph tags.<p>.linebreaksThe filter can convert newline characters in text to HTML paragraph and newline tags, whilelinebreaksbrit only converts them to<br/>. This is very useful for scenarios where precise control of text layout is desired.

Flexible data transformation: A symphony of types and formats

The original data types are diverse, but front-end display often requires a unified format. Filters also perform well in data type conversion and formatting.

Set a default value for empty data

This is the key to writing a robust template. When a variable may be empty,nil(null pointer) or zero value,defaultthe filter can provide a fallback value to avoid blank or error pages.default_if_nonespecialized fornilThe combination of both can cover most empty value scenarios.

For example, if the username is empty, display 'Anonymous User':{{ user.UserName | default:"匿名用户" }}

Fine-grained display of numbers

For price, statistics and other numerical information,floatformatThe filter can control the display accuracy of floating-point numbers, for example, retaining two decimal places.integerandfloatIt is used to convert a string to the corresponding numeric type to prevent type errors during calculation.

For example, to keep the price to two decimal places:{{ product.Price | floatformat:2 }}

The magnificent transformation of the timestamp

In AnQi CMS document data, time is usually stored in timestamp format.stampToDateThe tag is a powerful tool for processing timestamps, which can convert a 10-digit timestamp to any date-time format we want. Although it also hasdatea filter, but it requires that the variable is alreadytime.TimeType, for the original timestamp,stampToDateit is more convenient and direct.

For example, format the article publish time as "2023 January 01 12:30":{{ article.CreatedTime | stampToDate:"2006年01月02日 15:04" }}

Free switching between strings and arrays

When dealing with strings separated by commas or spaces, such as tags, keywords, etc.,splitThe filter can easily split it into an array (also known as slice), which is convenient for iterating over. On the contrary,joinThe filter can concatenate array elements into a string with a specified separator.make_listSplit strings into individual characters, andfieldsthen split by spaces.

For example, split the keywords of the article into an array and iterate to display:{% for tag in article.Keywords | split:"," %} <span>{{ tag }}</span> {% endfor %}

Guarding security and optimizing the experience: Advanced applications

In addition to basic text and data processing, filters play an important role in enhancing website security and user experience.

Proper handling of HTML and JS content.

The AnQi CMS defaults to automatically escaping template output to prevent XSS attacks. However, when displaying trusted content generated by a rich text editor (such as article details), we need to disable this escaping, at this timesafeThe filter is particularly important, as it tells the template engine: "This HTML is safe, please render it directly." Otherwise,escapeThe filter can explicitly escape HTML, whileescapejsIt is used specifically to escape special characters in JavaScript code. It can be used when controlling the escaping behavior of a large code block.autoescapeThe tag can be useful.

For example, display article content safely:{{ article.Content | safe }}

Intelligent beautification of URL addresses

urlizeThe filter can intelligently recognize URLs or email addresses in text and automatically convert them into clickable HTML links, while also adding by defaultrel="nofollow"Properties for optimizing SEO. If the link text is too long,urlizetruncit can be truncated to display the length of the URL. In addition,urlencodeandiriencodeThe filter is used to percent-encode URL parameters, ensuring the validity and security of the URL.

For example, automatically convert URLs in text to links: `{{ comment.Content |

Related articles

How does AnQi CMS generate and display thumbnails of different sizes for image resources?

In website operation, the loading speed and display effect of images directly affect user experience and search engine optimization.Especially for content management systems with a large number of images, how to efficiently generate and display thumbnails of different sizes is a crucial function.AnQiCMS (AnQiCMS) provides a flexible and powerful solution in this regard, making it easy to manage and display image resources. ### Core Advantage: Intelligent Generation and Flexible Upload AnQiCMS does a very good job in handling image resources.It is the most reassuring feature

2025-11-09

How to implement the correct rendering and style display of Markdown content in AnQi CMS template?

Markdown is favored by content creators for its concise and efficient characteristics.In AnQi CMS, using Markdown not only allows for quick content creation but also enables simple configuration to perfectly display these contents on the frontend page, including rich styles, mathematical formulas, and even flowcharts.This article will introduce in detail how to make your Markdown content render correctly and have a beautiful style in the Anqi CMS template.Enable Markdown editor First

2025-11-09

How does Anqi CMS ensure that static rules (such as model naming patterns) are correctly generated and displayed in URLs?

In website operation, a clear and friendly URL address not only allows visitors to understand the page content at a glance but is also an indispensable part of search engine optimization (SEO).A well-structured URL can help search engines better understand the page topic, thereby improving the crawling efficiency and ranking of the website.Our CMS deeply understands this, providing a simple, easy-to-use, and highly flexible solution for generating and displaying static rules.

2025-11-09

How to dynamically set the `title`, `keywords`, and `description` metadata of a page using the `tdk` tag?

In the practice of website operation and search engine optimization (SEO), page metadata plays a crucial role.Among them, the page title (`title`), keywords (`keywords`), and description (`description`) directly affect the display effect and the willingness of users to click on the search engine results page.AnQiCMS (AnQiCMS) fully understands its importance and provides a powerful and flexible `tdk` tag to help us dynamically and efficiently manage these key metadata.

2025-11-09

How does the `urlize` filter in AnQi CMS automatically convert URLs in text to clickable links?

In the daily content creation and website operation, we often need to insert various links in articles, whether they point to external resources or refer to other content within the site.Manually converting these plain text URL addresses into clickable hyperlinks is undoubtedly a repetitive and error-prone task.Imagine if the amount of content on the website were massive, how much time and effort would it take to do this job?

2025-11-09

How to display a user's comment list in AnQi CMS and support multi-level replies and review status distinction?

The comment feature is an indispensable part of a website's content and user interaction, as it not only enlivens the atmosphere of the website but also provides valuable user feedback to the operator.Anq CMS fully understands its importance and provides a flexible and feature-rich comment system that allows website administrators to easily display and manage user comments, while also supporting multi-level replies and review status differentiation to ensure the interactivity and quality of website content. ### Overview of AnQi CMS Comment Function In AnQi CMS, to display the comment list of website content, it mainly relies on its powerful template tag system.

2025-11-09

How to add captcha display to the comment feature of Anqi CMS to enhance security?

Maintaining a healthy, interactive website comment section is an indispensable part of content operation.However, comment sections often become hotbeds of spam and malicious attacks, which not only affects the quality of the website's content but also brings additional review burdens to website administrators.To effectively resist the interference of these automated programs, adding a captcha display to the comment feature of AnQi CMS is a simple and practical security enhancement measure.

2025-11-09

How can AnQi CMS display a list of recommended articles related to the current article content?

In website operation, providing a list of recommended articles related to the current content is an important strategy to enhance user experience, extend user stay time, and optimize website internal links.AnQiCMS (AnQiCMS) knows this and provides flexible and powerful features to help you easily achieve this goal.### Core Function Analysis: Related Document Tag `archiveList` To display a list of recommended articles related to the current article content in AnQi CMS, you will mainly use a very key template tag—`archiveList`

2025-11-09