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, ornilor 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.
Important reminder:Use<!-- 安全地输出 article.Content,使其作为 HTML 内容被浏览器解析 --> {{ article.Content|safe }}safeBe 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.
The AnQi CMS defaults to HTML escaping unless you use<!-- 将可能包含 HTML 标签的 userInput 转义,显示其原始代码 --> {{ userInput|escape }}safeorautoescape 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-->