In AnQiCMS template development, we often need to fine-tune the displayed content, such as extracting part of the information from a long text, or only displaying the first few elements from a list of data. Fortunately, AnQiCMS uses a class Django template engine that provides a very practical tool -slice[Slice] Filter, which can help us easily achieve these requirements.
sliceA filter is a very flexible feature that is not only applicable to string (text) but also to array (list) data.The core function is to extract a part of the original data according to the specified range.This is very useful for scenarios such as controlling the length of page content and filtering specific data segments.
sliceBasic usage of the filter
sliceThe syntax of the filter usage is very intuitive:{{ 变量 | slice:"起始索引:结束索引" }}.
The 'start index' and 'end index' here determine the range of the slice, and the following points should be noted:
- The index starts from 0Like most programming languages, the index in AnQiCMS templates also starts from 0. Therefore, the index of the first element or character is 0.
- The start index is included, the end index is not included.:
起始索引The specified position is the starting point of the截取 range (included in the result), and结束索引The specified position is the end point of the 截取 range (not included in the result). - Index can be omitted:
- If omitted
起始索引[for example]slice:":5"), then it starts cutting from the beginning of the data (index 0). - If omitted
结束索引[for example]slice:"5:"), then it continues cutting.起始索引Cuts to the end of the data at the specified position. - If both are omitted (for example,
slice:":"),will return the entire data (usually used for copying data).
- If omitted
- negative indices: Negative indices indicate counting from the end of the data. For example,
-1represents the last element/character,-2Means the second last, etc.slice:"-3:"Means to extract the last 3 elements/characters.slice:":-2"Means to extract all content except for the last 2 elements/characters.
Actual application example
Next, let's understand how to use AnQiCMS templates through specific examples.sliceFilter.
1. Extract a specified range of characters from a string.
Suppose you have a custom field.archive.DescriptionStored the article's summary. You only want to display the first 50 characters in the list page, and show the full summary on the detail page.
{# 假设 archive.Description 的值是 "AnQiCMS让网站运营更高效、可定制、易扩展,是中小企业和内容运营团队的首选工具。" #}
{# 显示前10个字符 #}
<p>简介(前10字):{{ archive.Description | slice:":10" }}</p>
{# 结果: 简介(前10字):AnQiCMS让网站运 #}
{# 从第5个字符开始,截取到末尾 #}
<p>简介(从第5字开始):{{ archive.Description | slice:"4:" }}</p>
{# 结果: 简介(从第5字开始):MS让网站运营更高效、可定制、易扩展,是中小企业和内容运营团队的首选工具。 #}
{# 截取第6到第15个字符 #}
<p>简介(第6到15字):{{ archive.Description | slice:"5:15" }}</p>
{# 结果: 简介(第6到15字):让网站运营更 #}
{# 截取最后8个字符 #}
<p>简介(最后8字):{{ archive.Description | slice:"-8:" }}</p>
{# 结果: 简介(最后8字):团队的首选工具。 #}
{# 截取除了最后5个字符之外的所有内容 #}
<p>简介(除了最后5字):{{ archive.Description | slice:":-5" }}</p>
{# 结果: 简介(除了最后5字):AnQiCMS让网站运营更高效、可定制、易扩展,是中小企业和内容运营团队的 #}
2. Slice the specified range of the array (list)
In AnQiCMS templates,archiveList/tagList/categoryListLabels usually return an array containing multiple data items. We can usesliceto control the number of displayed entries.
Suppose you havearchiveListretrieved a list of articlesarchivesYou only want to display the first three articles.
{% archiveList archives with type="list" limit="10" %}
<div class="article-list-section">
<h3>最新文章</h3>
<ul>
{% for item in archives | slice:":3" %} {# 只循环前3篇文章 #}
<li>
<a href="{{ item.Link }}">{{ item.Title }}</a>
<p>{{ item.Description | slice:":30" }}...</p> {# 再次对简介进行截取 #}
</li>
{% endfor %}
</ul>
</div>
{% endarchiveList %}
{# 进一步的例子:获取列表中从第二篇开始的四篇文章 #}
{% archiveList allArchives with type="list" limit="10" %}
<div class="featured-articles">
<h3>推荐文章(中间4篇)</h3>
<ul>
{% for item in allArchives | slice:"1:5" %} {# 索引1是第二篇,截取到索引5(不含),即第2、3、4、5篇 #}
<li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
{% endfor %}
</ul>
</div>
{% endarchiveList %}
3. Combine with other filters: convert the string to an array and then truncate
Sometimes, the data stored in a database may be a string separated by commas or other symbols, such as a list of keywords for an article: 'SEO optimization, content marketing, website security'.If you want to display only the first two keywords, you need to first convert the string to an array and then perform the slicing operation.
{# 假设 archive.Keywords 的值是 "SEO优化,内容营销,网站安全,模板定制" #}
{% set keywordArray = archive.Keywords | split:"," %} {# 使用 split 过滤器将字符串按逗号分隔成数组 #}
{% set firstTwoKeywords = keywordArray | slice:":2" %} {# 截取数组中的前两个元素 #}
<p>文章关键词:{{ firstTwoKeywords | join:" / " }}</p>
{# 结果: 文章关键词:SEO优化 / 内容营销 #}
{# 或者你可以将这些操作串联起来 #}
<p>文章关键词(简化版):{{ archive.Keywords | split:"," | slice:":2" | join:" | " }}</p>
{# 结果: 文章关键词(简化版):SEO优化 | 内容营销 #}
Tips
- Index out of bounds handling: In AnQiCMS templates,
sliceThe filter has good tolerance for index out of bounds.If the starting or ending index you specify exceeds the actual length of the data, it will not throw an error, but will return the content within the maximum valid range it can handle.|slice:":10"It will still return all 5 elements. If you request a non-existent range (such asslice:"10:12"), it will return an empty array or an empty string. - Improve the readability of temporary variable promotionWhen your template logic becomes complex, or you need to perform operations on the same slice result multiple times,
{% set 变量名 = ... %}This way of storing the slice result in a temporary variable can greatly improve the readability and maintainability of template code. - Data type match:
sliceThe filter is effective for both strings and arrays, but please ensure that your data type is indeed one of them. For numbers, booleans, etc.,sliceit may not produce the expected results.
By skillfully applyingsliceFilter, you can control the display of AnQiCMS website content more flexibly, making your template more powerful and dynamic.Why not try more in your project, and you will find its convenience.
Common Questions (FAQ)
Q1: In AnQiCMS template, if I try to access a string or an array by an index that exceeds its actual length, what will happen? Will it throw an error?
A1:No error. The template engine of AnQiCMS issliceThe index out of bounds in operation has a good error tolerance.If the range you specify exceeds the actual length, it will intelligently return the content within the maximum valid range it can handle.|slice:":10"It will still return all 5 elements if it slices the first 10, even if the specified range is completely beyond the data itself, for example, if you execute `|slice: '10'` on an array of 5 elements.