How to extract the specified starting and ending elements of a string or array in AnQiCMS template to achieve content segment extraction?

In AnQiCMS template design, sometimes we need to accurately extract a specific part from a long text or a data list.Whether it is extracting the abstract of an article, displaying several images in a carousel, or processing some elements in a data array, the flexible ability to extract fragments of strings and arrays is crucial.AnQiCMS powerful template engine, drawing on the syntax features of Django templates, provides us with a concise and efficient "filter" (Filters) to easily meet these needs.

Understanding the core:sliceFilter

To extract a specified segment of a string or array in the AnQiCMS template, the most core tool issliceFilter. This filter can 'slice' the part you need from the target data according to the start and end positions you set.

sliceFiltering basics:

{{ 目标数据 | slice:"起始位置:结束位置" }}

Here are the目标数据It can be a string, an array (or called a slice)."起始位置:结束位置"It is a string parameter, specified by the colon:to separate and specify the range to be截取.

Parameter details:

  • 起始位置(from):This is an integer representing the starting index (including the element at this position). The index starts from0Start counting. If omitted起始位置If not specified, it defaults to truncating from the beginning of the data. You can also use negative numbers, such as-1Represents the last element,-2Means the second last, etc.
  • 结束位置(to):This is an integer representing the end index of the cut (excluding the element at this position). If omitted,结束位置the default is to cut to the end of the data. With起始位置Similar, negative numbers can also be used to represent positions starting from the end.

Actual case demonstration:

Let's delve deeper through several examples.sliceThe application of filters.

  1. Extracting a substring fragment:Suppose we have a section of an article title and we want to display only the first few characters.

    {% set articleTitle = "安企CMS模板中灵活截取字符串和数组" %}
    
    
    {# 截取前五个字符 #}
    <p>标题前五字:{{ articleTitle | slice:"0:5" }}</p> {# 输出:安企CMS模板 #}
    
    
    {# 截取从第六个字符到末尾 #}
    <p>标题后半部分:{{ articleTitle | slice:"5:" }}</p> {# 输出:中灵活截取字符串和数组 #}
    
    
    {# 截取从倒数第五个字符到倒数第二个字符(不包含倒数第二个) #}
    <p>标题中间部分:{{ articleTitle | slice:"-5:-2" }}</p> {# 输出:字符串 #}
    
  2. Extracting elements from an array (slicing):假设我们有一个标签列表,只想显示其中的部分标签。这里我们会结合split过滤器将逗号分隔的字符串转换为数组,再使用joinThe filter converts the truncated array back to a string.

    {% set tagString = "网站运营,内容管理,SEO优化,模板开发,Go语言,前端技术,数据分析" %}
    {% set tags = tagString | split:"," %} {# 将字符串转换为数组 #}
    
    
    {# 截取前三个标签 #}
    <p>热门标签(前三):{{ tags | slice:"0:3" | join:" / " }}</p> {# 输出:网站运营 / 内容管理 / SEO优化 #}
    
    
    {# 截取从第二个到第四个标签(索引1到3) #}
    <p>精选标签(中间):{{ tags | slice:"1:4" | join:" | " }}</p> {# 输出:内容管理 | SEO优化 | 模板开发 #}
    
    
    {# 截取最后两个标签 #}
    <p>最新标签(最后):{{ tags | slice:"-2:" | join:" - " }}</p> {# 输出:Go语言 - 前端技术 #}
    

Combined with other practical filters

In the actual content segment extraction,sliceThe filter is often used in conjunction with other filters to achieve a more refined or user-friendly display effect.

  • splitFilter:When your data is stored in a single string with some delimitersplitCan convert it to an array, convenientsliceOperation. As shown in the above example.

  • joinFilter:After slicing the array segment, you may need to merge these elements back into a readable string,joinThe filter can be used. As shown in the above example.

  • lengthFilter:Understanding the length of a string or array before slicing can help you make conditional judgments or avoid slicing empty values.

    {% set imageUrls = ["/img/banner1.jpg", "/img/banner2.jpg", "/img/banner3.jpg", "/img/banner4.jpg"] %}
    {% if imageUrls | length > 2 %}
        {% for img in imageUrls | slice:"0:2" %}
            <img src="{{ img }}" alt="轮播图" />
        {% endfor %}
    {% else %}
        <p>图片数量不足,无法展示轮播。</p>
    {% endif %}
    
  • truncatecharsandtruncatewordsFilter:If your goal is to generate an article summary and you want to automatically add an ellipsis (…) after the excerpt,truncatechars(character truncation) andtruncatewordsThe auto content is truncated by word, which may be a better choice because it is specifically designed for this purpose.

    {% set longContent = "安企CMS是一个基于Go语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。项目定位于服务中小企业、自媒体运营者和多站点管理需求的用户,通过一套简洁高效的系统架构,支持多样化的内容展示和管理需求。" %}
    
    
    {# 截取前50个字符并添加省略号 #}
    <p>摘要:{{ longContent | truncatechars:50 }}</p>
    

    It is worth noting that when using rich text content containing HTML tags,truncatecharsorsliceBefore, it was common to first usestriptagsA filter to remove HTML tags to avoid truncation and damage to the HTML structure.

Summary

Master the templates in AnQiCMSsliceFilter, combinedsplit/join


Common Questions (FAQ)

1.slicefilters andtruncatecharsWhat are the main differences between the filters? sliceThe filter is a general-purpose slicing tool, which will accurately extract strings or arrays from specified positions without automatically adding ellipses (…). Andtruncatechars(or}truncatewords)The filter is specifically designed to create summaries, it will automatically add an ellipsis at the end after reaching a specified length, and it usually maintains better tag integrity when handling HTML.

2. What happens if I try to slice with a start or end position that goes beyond the actual range?AnQiCMS's template engine in processingsliceThe filter is very intelligent and robust.If the starting position you specify exceeds the data length, or the end position is less than the starting position, it will return an empty string/array according to the actual situation, or return the valid part as much as possible without causing a template rendering error.slice:"12:15"It will return an empty array, executionslice:"5:2"It will also return empty.

3.sliceFilter handles Chinese and English strings in the same way?Yes, the template engine of AnQiCMS is based on Go language and supports UTF-8 encoded characters well. This means that whether it is English letters or Chinese characters, in the `slice