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