Batch processing content: How to use `slice` to dynamically truncate strings of different lengths in a loop?

Calendar 👁️ 68

In website content operations, we often encounter situations where we need to display content in batches, such as article lists, product introduction summaries, and so on.To ensure the beauty of the page and the clarity of information presentation, we often need to truncate the titles or descriptions of these contents so that they can display different lengths in different areas or under different conditions.AnQiCMS (AnQiCMS) provides powerful template tags and filters, making this requirement simple and flexible.

Today, we will delve into how to useslicefilters or other related tools to dynamically truncate strings, thereby achieving more intelligent and expressive content presentation.

UnderstandingsliceFilter: The Foundation of Flexible Content Extraction

In the AnQi CMS template system,sliceIt is a very practical filter, mainly used to extract elements from a string or array at specified positions. Its syntax is concise and clear:

{{ obj|slice:"from:to" }}

HereobjRepresents the target string or array you want to extract.fromandtoSpecifies the start and end positions of the extract.

  • from: indicates the starting position of the extract (including this position). If omittedfromIt will start cutting from the beginning.
  • to: indicates up to which position (not including the position). If omittedtoIt will cut to the end.

For example, if you want to cut from a string"安企CMS内容管理系统"Extract the first five characters, you can write it like this:

{{ "安企CMS内容管理系统"|slice:"0:5" }}
{# 显示结果: 安企CMS内容 #}

If you want to extract from the fourth character to the end:

{{ "安企CMS内容管理系统"|slice:"3:" }}
{# 显示结果: CMS内容管理系统 #}

It is worth noting that,sliceThe filter can correctly handle UTF-8 encoded characters, which means you don't have to worry about乱码or half characters when dealing with Chinese characters.

Implement dynamic truncation in loops: Make content display smarter

sliceThe real power of filters lies in their ability to work with loop structures (such asforloops) and conditional judgments (such asifTags combined to achieve dynamic content truncation.This allows you to flexibly control the display length of content based on the characteristics of the content, its position in the list, or other business logic.

1. Based on the loop position, dynamic extraction:

Assuming you are displaying a list of articles, you want the title of the first article to be longer to attract user attention, while the titles of subsequent articles should display shorter summaries. You canforin a loopforloop.Counter(indicating the current loop index, starting from 1) to determine the position of the article and apply different truncation lengths.

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <li>
            <a href="{{item.Link}}">
                {% if forloop.Counter == 1 %}
                    {# 第一篇文章,标题截取较长 #}
                    <h3>{{ item.Title|slice:"0:30" }}...</h3>
                    <p>{{ item.Description|slice:"0:80" }}...</p>
                {% else %}
                    {# 其他文章,标题和描述截取较短 #}
                    <h4>{{ item.Title|slice:"0:15" }}...</h4>
                    <p>{{ item.Description|slice:"0:40" }}...</p>
                {% endif %}
            </a>
        </li>
    {% empty %}
        <li>暂无文章内容。</li>
    {% endfor %}
{% endarchiveList %}

In this example, we dynamically truncate the title and description according to the order of the articles in the list.

2. Set the truncation threshold based on the length of the content itself:

Sometimes, we do not want all the content to be forcibly truncated, but only when the content length exceeds a certain threshold. This can be achieved by combiningitem.Title|lengthetc. to judge.

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <li>
            <a href="{{item.Link}}">
                {% if item.Title|length > 25 %}
                    {# 标题超过25个字符才截取 #}
                    <h3>{{ item.Title|slice:"0:25" }}...</h3>
                {% else %}
                    {# 标题未超过,显示完整 #}
                    <h3>{{ item.Title }}</h3>
                {% endif %}

                {% if item.Description|length > 60 %}
                    {# 描述超过60个字符才截取 #}
                    <p>{{ item.Description|slice:"0:60" }}...</p>
                {% else %}
                    {# 描述未超过,显示完整 #}
                    <p>{{ item.Description }}</p>
                {% endif %}
            </a>
        </li>
    {% empty %}
        <li>暂无文章内容。</li>
    {% endfor %}
{% endarchiveList %}

Here we made use oflengtha filter to obtain the actual character length of the string, and combineifthe condition to decide whether to截取。“

slice/truncatecharswithtruncatewordsWhen to choose, how to combine?

In terms of content extraction, AnQi CMS not onlyslicebut also providestruncatecharsandtruncatewordstwo very useful filters. Understanding the differences can help you make more appropriate choices.

  • slice:It is suitable for the scenario where you need to control the range of truncation precisely, to obtain a specific part of a string or array. It does not add an ellipsis to the truncated content....), will not intelligently handle HTML tags. If your goal is to obtain a raw substring or subarray,sliceis preferred.
  • truncatechars:N: This filter will be based on the number of charactersNTo extract a string and automatically add an ellipsis at the end (...)NThe length of an ellipsis. It is more suitable for displaying article summaries, title previews, and providing a friendly 'to be continued' prompt.
  • truncatewords:N

Related articles

How to assign the result of a `slice` filter to a new variable for subsequent use?

In AnQiCMS template development, we often need to process displayed data in various ways, such as truncating a segment of text, or extracting specific items from a list.The `slice` filter is born for this, it can help us accurately slice a part of the string or array.However, it is not enough to simply extract data, how to conveniently assign the extracted results to a new variable for repeated use in the subsequent parts of the template or for more complex logic processing, this is the key to improving template development efficiency and code readability.### `slice` filter basics

2025-11-08

How to avoid Chinese garbled or incomplete truncation caused by the `slice` operation in AnQiCMS template?

When using AnQiCMS for website content development, you may sometimes encounter the situation where, when using the `slice` filter in the template to process Chinese content, the content is truncated and incomplete, which undoubtedly affects user experience and the accuracy of content presentation.Even though the underlying design of the system aims to avoid garbled characters, it is particularly important to understand its mechanism due to the characteristics of Chinese multi-byte characters and the expected display effects.

2025-11-08

Does Go template's `slice` filter support negative indices? How to use it to slice in reverse order?

In AnQiCMS, templates are the key to building dynamic content, allowing us to flexibly display data.In the process of template development, it is often encountered that string or list (usually slice in Go template, which can be understood as an array) truncation operations need to be performed.AnQiCMS provides a powerful `slice` filter to handle such needs.### Deeply understand the basic usage of `slice` filter The `slice` filter is mainly used to extract specified elements from strings or lists

2025-11-08

In AnQiCMS template, how to implement `slice` to extract a segment of content from a string?

In AnQi CMS template development, we often need to flexibly handle the displayed content, such as extracting key parts from a paragraph of text or simply displaying several items from the list.At this point, the `slice` filter is very practical.It can help us accurately extract a segment of content from the middle of a string or array (a slice in Go language).

2025-11-08

AnQiCMS development: Application scenarios of the `slice` filter in handling list pagination or displaying summaries?

In AnQiCMS template development, the `slice` filter is a very practical tool that allows us to perform precise slicing operations on strings (text) or arrays (lists).Mastering its usage can help you gain more flexible control when handling content display.The basic syntax of the `slice` filter is `{{obj|slice:"from:to"}}`.Here the `obj` is the string or array variable you want to process, and `from` and `to` define the start and end positions

2025-11-08

Template optimization: What is the difference between the `slice` filter and the `truncatechars` filter? When should you choose which one?

In Anqi CMS template development, we often need to control or truncate the displayed content to adapt to different layout requirements and optimize the user experience.At this point, the `slice` filter and `truncatechars` filter have become our commonly used tools.Although they can all achieve text slicing, there is a significant difference in functional focus and application scenarios.Understanding these differences can help us choose the appropriate filters more accurately, making the template code more efficient and the page display more reasonable.

2025-11-08

What result will the `slice` filter return when operating on an empty string or array?

In AnQi CMS template development, we often need to perform fine-grained control and processing of content.Among them, the `slice` filter is a very practical tool that allows us to extract the specified part from a string or array (usually referred to as a slice in Go language).This feature is very convenient when displaying article summaries, partial elements in pagination lists, or processing dynamic data.

2025-11-08

How to use the `slice` filter to get all elements of the array except the first and last?

When managing and displaying content in Anqi CMS, the flexibility of the template is the key to improving website operation efficiency.The built-in Django template engine syntax provides many practical filters, allowing us to handle various data in a concise and efficient manner.Today, let's delve deeply into a very practical filter——`slice`, which can help us accurately cut a specific part of an array (or called slice in the Go language environment), especially on how to get all elements except the first and last one.Content display is the core of website operation, whether it is an article list

2025-11-08