What is the correct syntax for using the `{{ obj|filter__name:param }}` filter in AnQiCMS templates?

Calendar 👁️ 66

AnQiCMS (AnQiCMS) provides strong support for content operation with its efficient and flexible features.In daily content display, we often need to process and format data in a fine-grained manner to ensure that information is presented in a **state to the visitors.At this time, the 'filter' in the template has become an indispensable tool for us.

Today, let's delve into the correct syntax of the filter usage in the Anqi CMS template:{{ obj|filter_name:param }}. Understand and master it, and it can make your website content show unprecedented professionalism and dynamism.

Filter: The 'refiner' of data presentation.

In the AnQi CMS template world, when you get a variable from the background (objWhen it may just be raw data. For example, a timestamp may need to be formatted as "October 26, 2023", a long text may need to be truncated with an ellipsis, or certain HTML content needs to be rendered safely.The filter is exactly born for these needs, it is like a 'refiner', which processes, converts, or verifies the original data, and then outputs the processed results.

Its basic syntax is very intuitive:

{{ obj|filter_name:param }}

Let's break down this structure:

  • {{ ... }}This is the standard double curly bracket syntax used in AnQi CMS template to output variable content. All data that needs to be displayed to the user will ultimately be output through it.
  • objThis represents the original variable or data object you need to process. It can be a string, number, array, or even a more complex structure.
  • |(pipe symbol)This symbol is the core of the filter, it indicates that the left side is inputtedobjand 'pipe' it to the rightfilter_name.
  • filter_nameThis is the name of the specific filter you want to apply, for exampletruncatechars(truncated character),date(Date formatting) orsafe(Safe HTML output).
  • :(Colon): If the filter needs additional parameters to work, this colon is used to separate the filter name and its parameters.
  • param(Parameter)This is an optional parameter passed to the filter. Different filters may require different types and quantities of parameters. Some filters may not require any parameters.

Understood the syntax, let's take a look at some common practical application scenarios.

Common filters and their usage examples

The AnQi CMS is built-in with rich filters that can meet all our daily content operation needs.

1. Default value handling:defaultwithdefault_if_none

When a variable may be empty or not exist, we do not want the page to display blank or error messages, in which case we can usedefaultordefault_if_nonea filter to set a fallback value.

  • defaultIf the variable is an empty string, zero, or nilor booleanfalsethen it will display the default value.
    
    <!-- 如果 userName 为空,显示 "大侠匿名" -->
    {{ userName|default:"大侠匿名" }}
    
  • default_if_none: More strictly, only if the variable isnil(i.e., in Go language)nilWhen the pointer type is empty, it displays the default value instead of treating an empty string or 0 as empty.
    
    <!-- 如果 userSignature 是 nil,显示 "这个人很懒,什么都没留下" -->
    {{ userSignature|default_if_none:"这个人很懒,什么都没留下" }}
    

2. Date and time formatting:date

Although AnQi CMS providesstampToDateLabel to format timestamps, but if your variable is alreadytime.Timeof type (usually passed directly by the backend),dateFilter is a more concise choice.

<!-- 将 createTime(假设为 time.Time 类型)格式化为 "2006-01-02" 格式 -->
{{ article.createTime|date:"2006-01-02" }}

Please note,dateThe filter follows the special date formatting rules of the Go language (for example, "2006-01-02 15:04:05" is a reference template and not the actual output).

3. Text Truncation:truncatecharsandtruncatewords

We often need to limit the display length of article summaries or abstracts while maintaining the continuity of reading.

  • truncatechars: Truncate text by character count, including an ellipsis.
    
    <!-- 截断 article.Description,最多显示 100 个字符,超出部分用 "..." 代替 -->
    {{ article.Description|truncatechars:100 }}
    
  • truncatechars_html: withtruncatecharsSimilar, but smarter, it will try to preserve the HTML structure.
    
    <!-- 截断 HTML 文本,并保持标签闭合 -->
    {{ article.Content|truncatechars_html:200|safe }}
    
  • truncatewords: Truncates text by word count, usually used for English content.
    
    <!-- 截断英文文本,最多显示 20 个单词 -->
    {{ article.Abstract|truncatewords:20 }}
    

4. Content Security and Rendering:safeandescape

It is crucial to prevent cross-site scripting (XSS) attacks when handling user input or rich text content.

  • safe: Tell the template engine that the content of this variable is safe HTML, which does not need to be escaped and can be rendered directly. It is commonly used for content generated by backend rich text editors.
    
    <!-- 安全地输出 article.Content,使其作为 HTML 内容被浏览器解析 -->
    {{ article.Content|safe }}
    
    Important reminder:UsesafeBe cautious, ensure the credibility of the content source, otherwise it may introduce security vulnerabilities.
  • escape:Force the content to be HTML-escaped, even if automatic escaping is already enabled, it will escape again. This helps to display the original HTML code instead of rendering it.
    
    <!-- 将可能包含 HTML 标签的 userInput 转义,显示其原始代码 -->
    {{ userInput|escape }}
    
    The AnQi CMS defaults to HTML escaping unless you usesafeorautoescape off.

5. Length Calculation:length

Get the length of a string, array, or map (number of elements).

<!-- 显示文章标题的字符数 -->
{{ article.Title|length }}

<!-- 显示评论列表中的评论总数 -->
{{ comments|length }}

6. String processing:add/replace/split/join

  • add: Add two numbers or concatenate strings.
    
    <!-- 数字相加 -->
    {{ price|add:discount }}
    <!-- 字符串拼接 -->
    {{ "欢迎使用"|add:"安企CMS" }}
    
  • replace: Replace a specific substring in a string.
    
    <!-- 将 article.Title 中的 "CMS" 替换为 "内容管理系统" -->
    {{ article.Title|replace:"CMS,内容管理系统" }}
    
  • split: Split a string into an array using a specified delimiter.
    
    <!-- 将逗号分隔的关键词字符串分割成数组 -->
    {% set tags_array = article.Keywords|split:"," %}
    {% for tag in tags_array %}
        <span>{{ tag }}</span>
    {% endfor %}
    
  • joinConcatenate array elements into a string with a specified delimiter.
    
    <!-- 将 tags_array 中的元素用 " | " 连接起来 -->
    {{ tags_array|join:" | " }}
    

7. Clean string:trim/trimLeft/trimRight

Used to remove spaces or specific characters from the beginning and end of a string.

  • trimRemove spaces or specified characters from both ends of the string. `twig{{"AnQi CMS"|trim}} <!-- Remove spaces from both ends of the string-->

Related articles

How to quickly remove spaces or specific characters from both ends, left or right of a string in AnQiCMS template?

In content management, we often encounter situations where there are excessive spaces or unwanted specific characters at both ends of strings, which not only affects the display aesthetics of the content, but also sometimes causes unnecessary interference to data processing or search engine optimization (SEO).AnQiCMS uses a template engine syntax similar to Django, providing us with concise and efficient filters (Filters) to easily solve these problems.This article will introduce how to quickly remove spaces or specific characters from both ends, left, or right of a string in the AnQiCMS template.

2025-11-07

How to implement capitalizing the first letter of each word in the article title in AnQiCMS templates?

In website content operation, the standardization of article titles is often a key factor in improving the professionalism and user experience of the website.A neat and consistent title format not only makes the content more attractive but also helps improve the overall image of the website.AnqiCMS provides us with a very concise and efficient solution, which can easily capitalize the first letter of each word in the article title with a simple filter in the template.

2025-11-07

How to force all English text in the AnQiCMS backend custom fields to lowercase?

In website content operation, maintaining consistency in text format is a key step to improving user experience and SEO effects.Sometimes, we may encounter such a need: we hope that the English text input in the custom field of the background, regardless of how the user inputs it in uppercase or lowercase, can be forced to lowercase when displayed on the front-end.This not only makes the page look neater and professional, but also helps avoid SEO problems caused by inconsistent capitalization.

2025-11-07

How to automatically capitalize the first letter of the English name submitted by the user in the AnQiCMS template?

In website operation, we often encounter the need to display user submitted information, such as name.In order for this information to look more professional and unified, it is usually desired that the first letter of the English name be automatically capitalized.This not only enhances the beauty of the user interface, but also ensures the consistency of data display.In the flexible template system of AnQiCMS, implementing this requirement is very simple.

2025-11-07

How to set a default friendly display value for a possibly empty variable in AnQiCMS template?

When building website templates, we often encounter situations where a variable may be empty in the template due to unentered data, optional fields left blank, or specific business logic.If these empty variables are not processed, the front-end page of the website may appear blank areas, display unfriendly placeholders, and even cause layout errors, thereby affecting user experience and the professionalism of the website.

2025-11-07

How to format a 10-digit timestamp retrieved from the database into a custom date-time format in AnQiCMS template?

In website content display, we often encounter time data in a long string of numbers from the database, such as `1678886400`. This string of numbers, which is what we commonly call a timestamp, is very convenient for computers, but it seems cold and difficult to understand for users visiting websites.Fortunately, AnQi CMS provides us with a very convenient feature that can easily convert these original 10-digit timestamps into the date and time format we are accustomed to reading.

2025-11-07

What are the main differences between AnQiCMS's `date` and `stampToDate` filters when handling date data?

In AnQiCMS template development, displaying time data is an indispensable part, whether it is the publication time of articles, the update date of products, or the time records of user behavior, it needs to be presented to the user in a clear and readable manner.To meet the different time processing needs, AnQiCMS provides two core filters: `date` and `stampToDate`.

2025-11-07

How to always display product prices (floating point numbers) with two decimal places in AnQiCMS templates?

When operating a product display website, you may often encounter situations where you need to display product prices accurately.A professional and user-friendly website often requires a unified display format for product prices, such as always retaining two decimal places, even for integer prices, which are automatically filled with `.00`. AnQiCMS with its flexible template system makes these details handling very convenient.

2025-11-07