In AnQiCMS template development, we often need to finely control the displayed content, such as extracting part of the text from a long string or displaying only the first few elements from a list. Fortunately, the class Django template engine adopted by AnQiCMS provides a very practical tool -sliceSlice filter, which can help us easily achieve these requirements.
sliceThe filter is a very flexible feature, it is not only suitable for strings (text), but also for array (list) data.Its core function is to extract a portion of the original data based on the specified range.This is very useful for controlling the length of page content, filtering specific data segments, and other scenarios.
sliceBasic usage of the filter.
sliceThe syntax of using filters is very intuitive:{{ 变量 | slice:"起始索引:结束索引" }}.
The "start index" and "end index" here determine the range of the slice, and the following points need to 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 includes, the end index does not include:
起始索引The specified position is the starting point of the截取范围的起点(包含在结果中),而结束索引The specified position is the end point of the截取范围的终点(不包含在结果中)。 - The index can be omitted:
- If omitted
起始索引for exampleslice:":5"Then it starts cutting from the beginning of the data (index 0). - If omitted
结束索引for exampleslice:"5:"Then it starts cutting from起始索引Cutting 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 index: Negative indices represent counting from the end of the data. For example,
-1represents the last element/character,-2representing the second to last, and so on.slice:"-3:"representing the last 3 elements/characters.slice:":-2"representing all content except the last 2 elements/characters.
Actual application example
Next, let's understand how to use the AnQiCMS template through specific examplesslicefilter.
1. Extract the specified range of the string
Suppose you have a custom fieldarchive.DescriptionStored the article summary, you want to display only the first 50 characters on the list page, and 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. Extract the specified range from the array (list)
In AnQiCMS template,archiveList/tagList/categoryListThe tag usually returns an array containing multiple items. We can usesliceto control the number of entries displayed
Assuming you pass througharchiveListGot a list of articlesarchives,You 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 other filters: Convert string to 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 convert the string to an array first, and then perform slicing operations.
{# 假设 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优化 | 内容营销 #}
温馨提示
- Index out of bounds handlingIn AnQiCMS template,
sliceThe filter has good tolerance for index out of bounds. If the start or end index you specify is beyond 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.For example, an array with only 5 elements, you execute|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. - Temporary variable enhances readabilityWhen your template logic becomes complex, or you need to operate on the same slice result multiple times, use
{% set 变量名 = ... %}This way of storing the slice result in a temporary variable can greatly improve the readability and maintainability of the template code. - Data type matches:
sliceThe filter works for strings and arrays, but make sure your data type is one of them. For numbers, booleans, etc.,sliceit may not produce the expected effect.
By mastering the use ofsliceFilter, 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.
Frequently Asked Questions (FAQ)
Q1: In AnQiCMS template, if I try to slice a string or array but the specified index exceeds its actual length, what will happen? Will it throw an error?
A1:No error. The template engine of AnQiCMS is forsliceThe 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.For example, if you have an array containing 5 elements, and you try to use|slice:":10"Slice the first 10, it will still return all 5 elements. If you specify a range that is completely beyond the data itself, such as an array of 5 elements you execute `|slice:“10