In AnQi CMS template design, Filters play a crucial role.As a senior website operations manager, I know that flexibly using these tools can greatly improve the quality of content presentation and user experience.The AnQi CMS template engine borrows syntax from Django, allowing content creators and template developers to conveniently process and format output data, without delving into backend code to achieve rich display effects.This article will discuss in detail the commonly used filter functions in Anqi CMS templates, especially around content extraction and replacement, and touch on some practical skills.

Content truncation and length control: An optimization tool for information display

In content operation, we often need to condense long text content to adapt to different display scenarios, such as displaying article summaries on list pages, extracting titles in recommendation modules, and so on.AnQi CMS provides a powerful text truncation filter that can precisely control the length of content while maintaining the cleanliness and readability of the page.

truncatecharsThe filter allows us to truncate a string based on character count.When the character count of the original string exceeds the specified limit, it will truncate the corresponding length of characters from the beginning and automatically add an ellipsis ("...") at the end.This is very useful for scenarios that require strict control of text display width, such as automatically shortening news list titles when they are too long.truncatewordsThe filter extracts words as units, which is particularly convenient when processing English or other languages separated by spaces, ensuring that the extracted text remains a complete word group rather than a half-word.

For content that includes HTML tags, directly using the above filter may destroy the HTML structure, causing the page to display abnormally. Therefore, Anqi CMS introducedtruncatechars_htmlandtruncatewords_htmlFilter.They intelligently maintain the integrity of HTML tags while extracting text, ensuring that the extracted content remains well-structured and correctly rendered as an HTML fragment in a browser.This is an indispensable function for retaining part of the format in article summaries or product descriptions.sliceThe filter provides more general slicing capabilities, whether it is a string or an array, it can obtain a part of its content by specifying the start and end indices, which provides additional flexibility when handling structured data.

Content transformation and formatting: achieving diverse content presentation

In addition to cutting, the Anqi CMS template filter also performs well in content conversion and formatting, meeting various needs from simple character processing to complex HTML structure adjustment.

In character processing,cutThe filter can remove specified characters from variables, which is very useful when cleaning specific symbols or spaces. For example, to remove all spaces from a string, you can use{{ "Hello world"|cut: " " }}. For case conversion and title formatting,upperandlowerconvert the text to uppercase and lowercase, respectively,capfirstand capitalize the first letter of the sentence.titleThe filter goes further, it will capitalize the first letter of each word in the string and the rest in lowercase, which is very suitable for formatting title output.

For the security and aesthetics of HTML content, Anqi CMS also provides a variety of filters.striptagsFilters can be like PHP'sstrip_tagsFunctions the same, strip all HTML, XML, and PHP tags, including HTML comments, to get pure text content. If you need to control it more finely,removetagsThe filter can remove specified HTML tags, retaining other tags, which is particularly useful for cleaning up specific unnecessary formats.linebreaksandlinebreaksbrThe filter can automatically convert line breaks in text to HTML tags<br/>for easy display of text content in paragraph form on web pages

in terms of special formatting and security processingstringformatThe filter provides functionality similar to Go languagefmt.Sprintf()that can format numbers or strings into the specified output format.urlizeThe filter automatically identifies URLs and email addresses in the text and converts them into clickable hyperlinks, while also addingrel="nofollow"Properties for optimizing SEO. If you need to truncate the displayed URL,urlizetruncYou can convert it to a link while replacing the part of the URL that exceeds the specified length with an ellipsis. To ensure the safety of the output content in JavaScript or HTML environments,escapejsThe filter will encode special characters in strings as\uxxxxandsafeThe filter is used to declare content as safe, which will not be automatically escaped by the template engine, thereby avoiding XSS attacks.

The Anqi CMS template filter also supports convenient conversion between lists and strings.joinThe filter can concatenate elements of an array into a string with a specified delimiter, andsplitThe filter can perform the opposite operation, splitting a string into an array with a specified delimiter.make_listThe filter can split a string directly into an array of characters, which provides convenience for character-level operations. Moreover,center/ljustandrjustThe filter can fill and align strings to achieve a specific layout effect.

Flexible application and combination

The filter design of AnQi CMS is very flexible, allowing developers to chain multiple filters together to form a powerful data processing chain. For example, you can first extract a segment of description, then convert it to plain text, and finally capitalize the first letter of the plain text:{{ article.Description|truncatechars:50|striptags|capfirst }}In addition, in addition to using variables directly after them|many filters can also pass through the symbol,{% filter %}and{% endfilter %}Label blocks can be applied to content within a code block, which provides a solution for more complex scenarios.

In summary, the filter function in Anqi CMS template is rich and practical, an indispensable toolset for website operators and template developers to enhance content display effects and optimize user experience.By mastering these filters, we can easily achieve fine-grained content control, dynamic display, and security processing, thereby creating a more attractive high-quality website.


Frequently Asked Questions (FAQ)

Q1: Why did I usetruncatecharsAfter the filter, the HTML tags were also truncated, causing the page to display abnormally? A1: truncatecharsThe filter is based on the number of plain text characters and does not recognize HTML tags. When you are dealing with content that contains HTML, if you use it directly,truncatechars,HTML tags may be truncated, thus breaking the page structure. To solve this problem, you should use a filter specifically designed for HTML content, such astruncatechars_htmlortruncatewords_htmlThese filters will intelligently retain the integrity of HTML tags while extracting text, ensuring the correct rendering of the page.

Q2: I want to display the timestamp stored in the database in the format "year-month-date hour:minute", which filter should I use? A2:In Anqi CMS template, you can usestampToDatetag functions to format timestamps. For example, if your timestamp variable is nameditem.CreatedTime, you can use it like this:{{stampToDate(item.CreatedTime, "2006-01-02 15:04")}}. Note that the formatting string2006-01-02 15:04The formatting of the time in Go language follows a rule, which is different from the commonYYYY-MM-DD HH:mmpattern.

Q3: How to safely output a variable containing HTML to a page without it being automatically escaped to plain text? A3:The AnQi CMS template engine defaults to automatically escaping HTML content to prevent XSS attacks. If you are sure that the variable content is safe and want it to be rendered as HTML code by the browser, you can add it after the variable|safea filter. For example:{{ archiveContent|safe }}This will inform the template engine that the content is 'safe' and does not require escaping. But please ensure the content source is reliable to avoid security risks.