AnQiCMS (AnQi Content Management System) provides strong support for content operations 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 to visitors in a **status**.The "filter" in the template has become an indispensable tool for us.
Today, let's delve into the correct syntax of using filters in the Anqi CMS template:{{ obj|filter_name:param }}Understand and master it, and your website content will show unprecedented professionalism and dynamism.
Filter: the 'refiner' of data presentation
In the template world of Anqi CMS, when you get a variable from the backend (objWhen it is, 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 may need to be rendered safely.The filter is designed for these needs, acting like a 'refiner', processing, converting, or validating the original data, and then outputting 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 templates for outputting 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 more complex structures.|(Pipe symbol)This symbol is the core of the filter, it indicates processing the left side into theobjinput to the "pipeline" on thefilter_nameright side.filter_nameThis is the name of the specific filter you want to apply,truncatechars(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(Parameters)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 filter 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 a blank or error, and in this case, we can usedefaultordefault_if_nonea filter to set a backup value.
defaultIf the variable is an empty string, zero value, ornilor booleanfalse, then the default value is displayed.<!-- 如果 userName 为空,显示 "大侠匿名" --> {{ userName|default:"大侠匿名" }}default_if_none: More strict, only when the variable isnil(i.e., in Go language)nilAn empty pointer is displayed as the default value when it is empty, and it does not treat an empty string or 0 as empty.<!-- 如果 userSignature 是 nil,显示 "这个人很懒,什么都没留下" --> {{ userSignature|default_if_none:"这个人很懒,什么都没留下" }}
2. Date and time formatting:date
Although the Anqi CMS providesstampToDateLabel to format timestamps, but if your variable is alreadytime.Timetype (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 the reference template, not the actual output).
3. Text Truncation:truncatecharsandtruncatewords
For article summaries or abstracts, we often need to limit their display length while maintaining readability.
truncatechars: Truncate text by character count, including the ellipsis.<!-- 截断 article.Description,最多显示 100 个字符,超出部分用 "..." 代替 --> {{ article.Description|truncatechars:100 }}truncatechars_html: withtruncatecharsSimilar, but more intelligent, it will try to preserve the HTML structure.<!-- 截断 HTML 文本,并保持标签闭合 --> {{ article.Content|truncatechars_html:200|safe }}truncatewords: Truncates text by word count, commonly 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.
safeTell the template engine that the content of this variable is safe HTML and does not need to be escaped; it can be rendered directly. Often used for content generated by backend rich text editors.
Important reminder:Use<!-- 安全地输出 article.Content,使其作为 HTML 内容被浏览器解析 --> {{ article.Content|safe }}safeBe cautious and ensure that the content source is trustworthy; otherwise, security vulnerabilities may be introduced.escapeForce the content to be HTML-escaped, even if automatic escaping is already enabled. This helps to display the original HTML code instead of rendering it.
The [en] default behavior of AnQi CMS is to escape HTML, unless you have used<!-- 将可能包含 HTML 标签的 userInput 转义,显示其原始代码 --> {{ userInput|escape }}safeorautoescape off.
5. Length Calculation:length
Get the length (number of elements) of a string, array, or map.
<!-- 显示文章标题的字符数 -->
{{ article.Title|length }}
<!-- 显示评论列表中的评论总数 -->
{{ comments|length }}
6. String Handling:add/replace/split/join
add: Add two numbers or concatenate two strings.<!-- 数字相加 --> {{ price|add:discount }} <!-- 字符串拼接 --> {{ "欢迎使用"|add:"安企CMS" }}replace[en]: Replaces 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 %}joinJoin 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 a string. `twig{{"Safety CMS" | trim}} <!-- Remove spaces or specified characters from a string -->