How to efficiently apply various data filters in Anqi CMS templates?

AnQi CMS, as an enterprise-level content management system built based on the Go language, has won the favor of many small and medium-sized enterprises and content operators with its high efficiency, security, and flexibility.In daily content management and frontend display, we often need to process and present data in a refined manner, which cannot be separated from the powerful data filtering function in the template.This article will delve into how to efficiently apply various data filters in the AnQiCMS template, making your content display more expressive and practical.

Understand the 'Data Filter' in Anqi CMS template

The AnQiCMS template engine borrows the design philosophy of Django, so for developers familiar with Django or similar template engines, the syntax will feel very familiar.In the AnQiCMS template, the data filter plays a role in converting and formatting variable values.They are like individual processing stations on a data pipeline, receiving raw data, undergoing specific processing, and then outputting a new format that meets the needs of the front-end display.

The syntax of using the data filter is very intuitive:{{ 变量 | 过滤器名称:参数 }}. Among them,|The symbol is the "pipeline" that connects variables and filters,过滤器名称indicating the operation to be performed, and:参数Provide additional configuration for the operation (if needed).

It is worth noting that in the AnQiCMS template, in addition to this 'pipe-style' filter, some tags themselves have data filtering functions, such asarchiveListTag throughcategoryId/order/typeImplement list filtering and sorting with parameters,archiveFiltersLabels are used directly to generate complex filtering conditions. Although their forms are different, the core purpose is to achieve precise data acquisition and flexible display.

Why is it crucial to efficiently apply data filters?

Efficiently applying data filters in Anqi CMS can bring various advantages:

  1. Improve the quality of content presentation:No matter if it is a truncated introduction or a date with a specific format, the filter can display data in the most suitable way for the front-end interface, improving the user's reading experience.
  2. Enhance the readability and maintainability of template code:By processing data through a filter, you can avoid writing complex programming logic in the template, making the template code more concise and readable.When the data processing rules change, it is only necessary to modify the filter parameters or replace the filter, rather than make extensive changes to the template structure.
  3. Ensure the security of data display:The filter can effectively prevent XSS attacks, format errors, and other issues for user input, ensuring the security and stability of the website.
  4. Achieve more flexible data interaction:Combine various filters to easily convert backend data into the format required by frontend components, such as converting strings to arrays for list rendering, or formatting numbers as currency.
  5. Optimize SEO performance:By filtering the title, description, and other content, truncation, keyword highlighting, and other processing can help generate content snippets that are more in line with search engine optimization requirements.

The commonly used data filter and its efficient application in Anqi CMS

The Anqi CMS provides a variety of data filters covering text, numbers, dates, HTML processing, and more. Below, we select some of the most commonly used and practical filters and illustrate them with actual application scenarios:

1. Text processing and formatting: Making text elegant

  • truncatecharsandtruncatewords: Smart text truncationThese two filters are very useful when we need to display a summary or preview of the content.truncatechars:数字It will be truncated based on the number of characters, whiletruncatewords:数字it will be truncated based on the number of words. If the truncated text exceeds the specified length, it will automatically add an ellipsis at the end...Make sure the HTML tags are complete.

    • Example of high-efficiency application:
      
      {# 截取文章描述的前50个字符 #}
      <p>{{ item.Description|truncatechars:50 }}</p>
      {# 截取HTML内容的前20个单词,常用于文章列表,避免布局错乱 #}
      <div class="summary">{{ item.Content|truncatewords_html:20|safe }}</div>
      
  • capfirst,lower,upper,title: The art of case conversionThese filters are used to control the case of text.capfirstCapitalize the first letter of a string,lowerConvert to lowercase,upperConvert to uppercase,titleThen capitalize the first letter of each word.

    • Example of high-efficiency application:
      
      {# 将用户输入的标签转换为统一格式,如“product category”变成“Product Category” #}
      <span>{{ tag.Title|title }}</span>
      {# 确保导航菜单项统一显示为大写 #}
      <a href="{{ nav.Link }}">{{ nav.Title|upper }}</a>
      
  • cutandreplace: Precise replacement and deletion cut:关键词Used to remove all occurrences of a specified keyword from a string.replace:旧词,新词It is used to replace one word with another in a string.

    • Example of high-efficiency application:
      
      {# 移除文章标题中的特定前缀,如“【原创】” #}
      <h3>{{ archive.Title|cut:"【原创】" }}</h3>
      {# 将联系电话中的连字符替换为空格 #}
      <p>电话: {{ contact.Cellphone|replace:"-," }}</p>
      
  • trim,trimLeft,trimRight: Remove extra spaces or characters.These filters can remove whitespace characters from the beginning, end, or both ends of a string, and even specify specific characters to be removed.

    • Example of high-efficiency application:
      
      {# 清除用户输入关键词前后可能存在的空格 #}
      <input type="text" value="{{ search.query|trim }}">
      {# 删除URL路径开头多余的斜杠 #}
      <img src="/{{ imagePath|trimLeft:"/" }}" alt="">
      

2. Data type conversion and calculation: bring data to life.

  • add: Simple addition operation add:另一个值The filter can add numbers or strings. Numbers will be added mathematically, and strings will be concatenated.

    • Example of high-efficiency application:
      
      {# 在页面显示下一个月的日期 #}
      {% set currentMonth = now("01"|integer) %}
      <p>下个月是: {{ currentMonth|add:1 }} 月</p>
      {# 拼接CSS类名 #}
      <div class="item-{{ forloop.Counter|add:1 }}"></div>
      
  • integerandfloat: Flexible data type conversionThese filters can force the variable value to be converted to an integer or a floating-point number. This is very useful in scenarios involving mathematical operations or when a specific data type is required.

    • Example of high-efficiency application:
      
      {# 确保传入计算的参数是整数 #}
      {% set total = item.Price|float * item.Quantity|integer %}
      
  • **stringformatCustom format: