How does AnQiCMS's `filter` tag combine multiple filters to process content in a chain?

Calendar 👁️ 71

AnQiCMS provides flexible and powerful content management capabilities, with the template engine being the core of our daily operations and content display.When processing website content, we often encounter situations where we need to perform multiple transformations to achieve the final display effect.For example, a long article summary may require us to first cut a part of it, then ensure all letters are lowercase, and finally calculate the length of the processed result.If each time is handled manually through complex code logic, it is not only inefficient but also makes the template difficult to maintain.

At this time, in the AnQiCMS template engine,filterThe label chaining processing function is particularly important, it allows us to connect multiple filters like a pipeline, perform continuous, sequential transformations on the content, greatly improving the efficiency and flexibility of content processing.

Understand AnQiCMS's "filter"

Before delving into chained processing, let's briefly review what the 'filter' is in AnQiCMS templates.In simple terms, a filter is a tool that converts or processes variable values.|Followed by the filter name and optional parameters to use, the format is usually{{ 变量名|过滤器名称:参数 }}.

For example, we want to convert a piece of text to lowercase:

{{ "HELLO WORLD"|lower }}
{# 输出结果:hello world #}

Or, we want to cut the first 50 characters of the article abstract:

{{ archive.Description|truncatechars:50 }}
{# 输出结果:[文章简介的前50个字符]... #}

Each filter focuses on completing a specific content transformation task. They are the basis for building flexible templates.

Chain processing: When a filter is not enough

In practical work, a single filter often cannot meet the needs of complex content processing.Imagine a scenario: we need to display the summary of a news article.This summary first needs to extract the first 100 characters, then to unify the style, all letters need to be converted to lowercase, and finally, we may also need to count the number of characters in the final displayed text to ensure it meets the design requirements.

If there is only one filter, we may need to proceed step by step, or perform preprocessing in the background, which undoubtedly increases complexity. But havingfilterThe label's chaining processing capability makes everything exceptionally concise and efficient.

In AnQiCMS templates, the implementation of chain processing is very intuitive, just add a vertical line after the output of the first filter|and the next filter.Data will pass through each filter from left to right and the output of the previous filter will be the input for the next filter.Just like a content processing 'assembly line', the original manuscript enters the first stage for processing, and the semi-finished product after processing enters the next stage until all stages are completed, ultimately presenting content that meets the requirements.

Let's look at an example described just now:

{{ "这是很长的一段内容,需要先截断,再转换为小写字母,最后计算长度。"|truncatechars:10|lower|length }}

The execution process of this code is as follows:

  1. "这是很长的一段内容...": The original string is the starting point.
  2. |truncatechars:10: First,truncatecharsThe filter will truncate the first 10 characters of the string (including an ellipsis), for example, it becomes"这是很长的一段...".
  3. |lower: Next, the string truncated in the previous step"这是很长的一段..."aslowerThe input of the filter, which converts the English letters to lowercase. If the original string does not contain any English, this step may not have a significant change, but it is still processed.
  4. |length: Finally, after slicing and case conversion, the string is used aslengththe input for the filter to calculate the final number of characters.

In this way, the task that originally required multiple lines of code or complex logic is elegantly condensed into a single template line, making it clear and easy to understand.

Chain filters in practical applications

Chain filters have a wide range of application scenarios in AnQiCMS content operations:

  1. Cleaning and beautifying text content:When displaying user submitted comments or externally imported content, we often need to remove extra spaces, unify case, or replace sensitive words.
    
    {# 去除首尾空格 -> 转换为小写 -> 替换敏感词 #}
    {{ "  用户输入的内容包含了一些 敏感词语 " | trim | lower | replace:"敏感词语,***" }}
    
  2. Process image URL and description:When displaying an image, we may need to obtain its thumbnail version, convert its alt attribute to uppercase, or truncate part of the description.
    
    {# 获取图片地址的缩略图版本,并确保描述文本大写 #}
    <img src="{{ item.Logo|thumb }}" alt="{{ item.Title|upper }}">
    
  3. Date and time formatting:Convert a UNIX timestamp to a date string in a specific format and possibly further process it.
    
    {# 将时间戳格式化为“年-月-日 时:分”,然后截取前 16 位 #}
    {{ item.CreatedTime|stampToDate:"2006-01-02 15:04:05"|slice:":16" }}
    
  4. Intelligent extraction of HTML content:If the article content contains HTML tags, use them directlytruncatecharsIt will destroy the tag structure. At this point,truncatechars_htmlandsafefilter combinations are very practical.
    
    {# 截取带HTML的内容并保持HTML结构完整,然后标记为安全输出 #}
    {{ article.Content|truncatechars_html:200|safe }}
    
    Here|safeThe role is particularly critical, it tells the template engine that it has been processedtruncatechars_htmlThe content after processing is safe HTML and does not need to be automatically escaped. It can be rendered directly on the page. This avoids<p>标签</p>displayed as&lt;p&gt;标签&lt;/p&gt;the question.

Why are chained filters so important?

  • Improve code efficiency and readability:Merge multiple operations into a single line, reducing redundant intermediate variables and complex nested logic, making the template code more concise and easy to understand.
  • Enhance the flexibility of content processing:To meet different content display requirements, we can quickly achieve diverse content presentation effects by adjusting the combination order or parameters of the filters, without modifying the underlying data.
  • Simplify template logic:The template focuses on data display, handing over complex transformation logic to the filter chain, making the template code more in line with its positioning as a 'presentation layer'.
  • Helping SEO and user experience:Precision control over page elements such as titles, descriptions, and keywords can help improve search engine friendliness; optimized content presentation can also provide a better user reading experience.

Tips for using chained filters

  1. Execution order is crucial:Remember, the filter chain always executes from left to right. Changing the order can lead to completely different results. For example, firstlowerthentruncatecharsFirsttruncatecharsthenlowerThere may be differences.
  2. Understand the input and output of each filter:When building a chain, ensure that the output type of the previous filter matches the expected input type of the next filter, otherwise errors or unexpected results may occur.
  3. Use it well when processing HTML content|safe:Any filter that modifies HTML content (such as truncation or replacement) after it, if you want the browser to render these HTML tags correctly rather than displaying them as plain text, it is usually necessary to add|safefilter.
  4. Step-by-step debugging:If the chained filter is not working as expected, try to break it down, test the output of each filter individually, and find the problem.

Summary

AnQiCMS'filterThe tag chaining processing function undoubtedly provides a powerful tool for content operators and website developers.It makes complex content conversion tasks simple and efficient, and endows the template with great flexibility, helping us focus more on the presentation effect of the content, thereby better serving the users and business goals of the website.By cleverly combining and applying these filters, we can achieve more refined and personalized content display on websites built with AnQiCMS.


Frequently Asked Questions (FAQ)

1. Do the execution order of chained filters always go from left to right?Yes, the chained filter is executed strictly from left to right.The output of the previous filter will be used as the input for the next filter.Therefore, it is very important to understand the function of each filter and its position in the chain, because changing the order can lead to very different final results.

2. Can I chain any type of filters together?In theory, as long as the output type of the previous filter is compatible with the input type of the next filter, it can be chained together.AnQiCMS's template engine is designed to be relatively intelligent, capable of handling common type conversions.But if you try to combine incompatible types (such as passing a boolean value to a filter that expects a string), it may result in the filter being ignored, returning null, or producing an error.Suggest to understand the expected input and output of each filter before using it.

3. Why is it necessary to pay special attention when processing HTML content?|safeFilter?AnQiCMS (and many other template engines) perform HTML entity encoding on all output content for security reasons. This means that if you directly output<p>内容</p>Such an HTML string, it will be converted to&lt;p&gt;内容&lt;/p&gt;and displayed as plain text on the page instead of being rendered

Related articles

What search engines does the "Link Push" feature of AnQiCMS backend support for active push?

Today, with the rapid growth of internet content, the quick inclusion of website content is an important factor in increasing website traffic and influence.For many content operators and enterprises, how to make search engines discover and index new content on their websites in a timely manner is a core issue in SEO work.AnQiCMS (AnQi CMS) deeply understands this need, especially in the backend, integrating a convenient and powerful "link push" function, aimed at helping users deliver their carefully crafted content to major search engines in the shortest possible time, effectively shortening the cycle from content publication to indexing.###

2025-11-08

How to use the `length` filter to get the length of a string, array, or key-value pair in AnQiCMS templates?

In AnQiCMS template development, we often need to process and judge the data displayed on the page.Among them, getting the length of a string, array, or key-value pair is a very basic and practical operation.The AnQiCMS template engine provides the `length` filter, making this task simple and intuitive. ### Understanding the `length` filter: A tool for getting data length The `length` filter, as the name implies, is used to get the 'length' of the data.

2025-11-08

How do the `urlize` and `urlizetrunc` filters handle URL links in the AnQiCMS template?

In website operation, we often need to embed various links in the content, whether they point to internal resources or external references.Manually converting plain text links into clickable hyperlinks is not only inefficient but also prone to errors.It is more important that standardized link handling is crucial for search engine optimization (SEO) and user experience.

2025-11-08

How to format timestamp output to date or time string in AnQiCMS template?

In website operation, the date and time information of content publication, update, and other aspects are crucial for user experience and content management.AnQiCMS as a rich-featured content management system, provides flexible template tags, allowing users to easily format the timestamp data stored in the background into various easily readable date or time strings to meet different display requirements.

2025-11-08

How to customize the front-end content display layout of Anqi CMS website?

AnQiCMS provides highly flexible frontend content display layout customization capabilities, allowing websites to present unique visual effects and information structures according to specific needs.This is not only about the appearance of the website, but also about how to deliver content efficiently and accurately to visitors.By understanding the template mechanism and various functions of AnQiCMS, users can easily achieve fine-grained control from the overall theme style to the display of single content.

2025-11-08

How can AnQi CMS be configured and display multilingual content to expand the international market?

Expand the international market, allowing your content to reach global users is an important part of many enterprises' digital strategies.AnQiCMS (AnQiCMS) is well aware of this need and therefore built-in strong multilingual support and multi-site management capabilities from the very beginning, helping users efficiently configure and display multilingual content. ### Embarking on the journey of internationalization: The cornerstone of multilingual support AnQi CMS is committed to providing small and medium-sized enterprises and content operation teams with an efficient and flexible content management platform.

2025-11-08

How to optimize the URL structure of Anqi CMS to improve search engine results?

In the world of digital marketing, a website's URL is not just a string of addresses; it is also the key for users and search engines to understand the content of the web page.A well-optimized URL structure not only enhances user experience but also significantly improves the website's crawling and ranking performance by search engines.For those who operate websites using AnQi CMS, using the powerful functions provided by the system to optimize the URL structure is an important step to improve the display effect of search engine results.Why is optimizing URL structure so important?

2025-11-08

How to set an independent display template for a specific page or content block in AnQi CMS?

In the daily operation of Anqi CMS, we often encounter such needs: certain pages or content need to break away from the unified style of the website and present in a unique way.This could be to highlight an important product, create a dedicated landing page for a special topic event, or simply make the "About Us" page more brand-specific.

2025-11-08