What are the common functions of filters in AnQiCMS templates (such as truncation, replacement)?

Calendar 👁️ 56

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.

Related articles

How to format timestamp output in AnQiCMS template?

As a professional familiar with Anqi CMS and proficient in content operation, I know that accuracy and beauty in website content display are crucial.A clear and easy-to-read timestamp that not only improves user experience but also reflects the standardization of data display.Below, I will give you a detailed introduction on how to format timestamp output in AnQiCMS template.

2025-11-06

How to perform conditional judgments (if/elif/else) in Anqi CMS template?

As an experienced CMS website operation personnel, I am well aware that the flexibility of templates is crucial for efficient operation in daily content management.Especially conditional judgment allows us to intelligently control the display and hiding of content based on different data states and business logic, thereby providing users with a more accurate and personalized browsing experience.The Anqi CMS template engine has adopted the syntax style of Django, making the implementation of conditional judgments both powerful and easy to understand.### The basic structure of conditional judgment in AnQi CMS template Conditional judgment in the AnQi CMS template is mainly achieved through

2025-11-06

How to use the for loop in AnQiCMS template to traverse data and handle empty results with the empty tag?

## Master the data traversal and empty result handling in AnQiCMS templates: in-depth analysis of for loops and empty tags AnQiCMS, with its efficient and customizable features, has become the preferred content management system for many content operation teams and small and medium-sized enterprises.It is crucial for the flexibility of template language when building dynamic web pages.

2025-11-06

How to display the list of related documents in AnQiCMS template?

As a website operator who has been deeply involved in the CMS of security enterprises for many years, I know that effectively guiding users to discover more interesting content is crucial for enhancing user stickiness and the depth of website visits.Among them, the 'related document list' is undoubtedly one of the core functions to achieve this goal.It not only helps users conveniently explore more related topics, but also has a positive impact on the internal link structure of the website and SEO optimization.

2025-11-06

How to implement string concatenation and array splitting in AnQiCMS templates?

AnQiCMS is an efficient and flexible content management system, whose powerful template engine provides a solid foundation for the dynamic display of website content.In daily content operation and template development, we often need to concatenate strings or split a string into multiple parts for processing according to specific rules.For example, building dynamic links, combining display information, or displaying the comma-separated tag list from the background data on the front end separately.Master the ability to concatenate strings and split arrays in AnQiCMS templates, which can greatly enhance the flexibility and expressiveness of the template

2025-11-06

How does AnQiCMS Markdown editor support math formulas and flowchart display?

As an experienced website operator proficient in the AnQi CMS content management system and with a keen perception of user needs, I am delighted to elaborate on how the AnQi CMS Markdown editor supports the display of mathematical formulas and flowcharts.Anqi CMS is committed to providing users with an efficient and flexible content management experience, and understands the importance of precise expression of mathematical formulas and clear presentation of flowcharts in specific fields (such as academic, technical blogs, or project management).

2025-11-06

How to deploy AnQiCMS using Docker, for example with 1Panel or aaPanel?

As an experienced website operator familiar with Anq CMS, I fully understand the importance of efficient deployment for enterprise content management.AnQiCMS with its efficiency in Go language, flexible customization capabilities, and easy scalability, has become an ideal choice for small and medium-sized enterprises and content operation teams.By combining Docker technology, the deployment experience of AnQiCMS has been significantly improved, especially with the assistance of panels like 1Panel or aaPanel, making the entire process unprecedentedly convenient and efficient.##

2025-11-06

What is the focus of the latest project of AnQiCMS core developer Fesiong?

As a website operator who deeply understands the operation of AnQiCMS, I know the importance of a powerful and flexible CMS system for content creators.Regarding the latest project focus of AnQiCMS core developer Fesiong, we can see his profound strategic considerations from the positioning, technical advantages, and recent update logs of AnQiCMS.**Fesiong: Building safety as a foundation, empowering small and medium-sized enterprises in content operation** The birth of AnQiCMS

2025-11-06