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 |