In the daily operation of AnQi CMS, we often encounter scenarios where we need to display content in a refined manner.How to flexibly extract the part we want from strings or lists, whether it is abstracts of articles, lists of product parameters, or extracts of user comments, is the key to improving user experience and page cleanliness.As an experienced website operations expert, I am well aware of the power and flexibility of AnQiCMS based on Go language and Django template engine. Today, let's delve into how to accurately extract a specific part of a string or list in AnQiCMS templates.

The core tool for precise extraction:sliceFilter

AnQiCMS's template engine provides us with a variety of powerful filters, where,sliceThe filter is undoubtedly the core tool for achieving precise extraction of the specified part of a string or list. Its design is simple and efficient, making it easy for us to meet various data extraction needs.

Imagine you have a long article content, but you only want to display the first few words as a summary on the list page; or you have a list of product image URLs and you only want to display specific ones.slicethe filter can come into play.

sliceThe filter is very intuitive to use, its basic syntax is{{ obj|slice:"from:to" }}Here,objIt can be any string, array (slice) or list."from:to"It defines the part we want to extract:fromSpecify the starting index (inclusive of the element at this position),toSpecify the ending index (exclusive of the element at this position). It is worth noting that the index is counted from 0.

For example, if we have a string “Welcome to AnQi CMS, an efficient content management tool!” and we want to extract the part “AnQi CMS”, we can do it like this:

{# 假设我们有一个变量 articleTitle = "欢迎使用安企CMS,高效内容管理利器!" #}
{% set articleTitle = "欢迎使用安企CMS,高效内容管理利器!" %}
<p>完整标题:{{ articleTitle }}</p>
<p>截取后:{{ articleTitle|slice:"6:11" }}</p>

After running, the page will display:

完整标题:欢迎使用安企CMS,高效内容管理利器!
截取后:安企CMS

Here are the6:11The content starts from the index of 6 (i.e., the character “安”), and ends before the index of 11 (i.e., the character “高” before it), thus cutting out “安企CMS”.

sliceThe filter is also very flexible. If you want to cut from the beginning to a certain position, you can omit itfromfor exampleslice:":11"It will start cutting from the beginning to index 11. If you want to cut from a certain position to the end, you can omit it.tofor exampleslice:"6:"It will start cutting from index 6 to the end of the string.

In addition, it also supports negative indices, which is very practical in certain scenarios. For example,slice:"-3:"means that it starts from the third character from the end and extracts to the end,slice:":-3"It indicates to cut from the beginning to the third character from the end.

For the cutting of a list or array,sliceThe usage of filters is also the same.archiveListThe label has retrieved a list of documents and wants to display only the first three documents:

{% archiveList recentArchives with type="list" limit="10" %}
    {# 假设这里获取了10篇文档,我们想展示前3篇 #}
    {% for doc in recentArchives|slice:":3" %}
        <h3>{{ doc.Title }}</h3>
        <p>{{ doc.Description }}</p>
    {% endfor %}
{% endarchiveList %}

Pass|slice:":3",we cleverly truncated the original list, keeping only the first three documents, making the page display more focused.

Assistant truncation: firstandlastFilter

ExceptsliceThis general method of truncation, AnQiCMS also provides us with a more concisefirstandlastFilter used to quickly obtain the first character of a string or the first element of a list, as well as the last character of a string or the last element of a list.

When you only need the first item from a list or the first character of a string, using them will be more convenient.sliceIt will be more convenient.

{% set someString = "Hello AnQiCMS" %}
<p>字符串第一个字符:{{ someString|first }}</p>
<p>字符串最后一个字符:{{ someString|last }}</p>

{% archiveList docs with type="list" limit="5" %}
    {# 假设 docs 是一个文档列表 #}
    {% set firstDoc = docs|first %}
    <p>第一篇文档标题:{{ firstDoc.Title }}</p>
{% endarchiveList %}

The result will clearly display the "H" and "S" in the string, as well as the title of the first document.

Elegantly handle content overflow:truncatecharsandtruncatewordsFilter

In many cases, we extract strings to generate content summaries and we hope to automatically add ellipses when the content is too long. AnQiCMS providestruncatecharsandtruncatewordsA series of truncation filters.

truncatecharsThe filter will truncate by character count, and if the content exceeds the specified character count, it will add “…” at the end.It should be noted that the specified length includes the ellipsis.|truncatechars:20It ensures that the output string (including ellipsis) is at most 20 characters.

truncatewordsThe filter then truncates based on the number of words, and an ellipsis is also added when the content overflows.

These filters are especially suitable for the abstract display on the article list page, ensuring a tidy layout while hinting at the completeness of the content.

{% set longDescription = "AnQiCMS 是一个基于 Go 语言开发的企业级内容管理系统,致力于提供高效、可定制、易扩展的内容管理解决方案。" %}
<p>字符截断摘要:{{ longDescription|truncatechars:30 }}</p>
<p>单词截断摘要:{{ longDescription|truncatewords:10 }}</p>

The output may be similar to:

字符截断摘要:AnQiCMS 是一个基于 Go 语言开发的企业级内容...
单词截断摘要:AnQiCMS 是一个基于 Go 语言开发的企业级内容管理系统...

For content containing HTML tags, AnQiCMS also takes this into account and providestruncatechars_htmlandtruncatewords_htmlFilters that can intelligently maintain the integrity of HTML tags while truncating, avoiding chaos in the page structure due to truncation.

Flexible combination:splitWithjoinFilter

Sometimes, we need to perform more complex operations on a string, such as when it itself is a comma-separated string, and we want to treat it as a list to truncate, and then recombine.splitandjoinThe filter can be used to separate.sliceThey can perfectly match with.

splitThe filter can split a string into an array using a specified delimiter. For example,"apple,banana,orange"|split:","an array containing three elements will be obtained.

joinThe filter does the opposite, it concatenates an array into a string using the specified delimiter.

{% set tagsString = "SEO,网站优化,内容营销,Go语言" %}
{# 先将字符串拆分成数组,然后截取前两个,再重新拼接 #}
{% set firstTwoTags = tagsString|split:","|slice:":2"|join:" / " %}
<p>精选标签:{{ firstTwoTags }}</p>

The output will be:

精选标签:SEO / 网站优化

This combination operation greatly expands our ability to handle data in templates, making originally complex string and list operations simple and intuitive.

In summary, the template engine of AnQiCMS provides web operators with extremely flexible and powerful content control capabilities. Whether it is accurate to characters,sliceExtract, or is it born to generate a summary?truncatecharsor withsplit/joinAccompanying the implementation of complex data conversion, these filters are indispensable tools in our hands.By proficiently utilizing these functions, we can ensure that the display of website content always conforms to the design expectations, enhancing the user's browsing experience.

Common Questions (FAQ)

1. Why should I usesliceInsteadtruncatecharsto extract strings?ChoosesliceOrtruncatecharsIt depends on your specific needs. If you need to extract a specified range of content from a string accurately, and do not need to automatically add an ellipsis (…) after the cut.sliceIt is a more suitable choice. It provides pure interval extraction.truncatechars(or}truncatewords) is specifically used for generating summaries. It will automatically add an ellipsis at the end of the content when it is too long._htmlVariants can intelligently handle HTML tags and avoid destroying the structure. In short,sliceFocus on 'which part to take'.truncatecharsFocus on 'how long and with hints'.

2.sliceCan the filter correctly handle strings containing Chinese?Yes, AnQiCMS's template engine takes into account the characteristics of UTF-8 encoding when processing strings, thereforesliceFilter can correctly cut Chinese characters.An English character is considered as one character, regardless of how many bytes it occupies internally, you can cut Chinese character strings as accurately as English characters by using indexes.

3. If I giveslicethe filter inputfromortoWhat happens if the index exceeds the actual length of the string or list?AnQiCMSsliceThe filter will perform safe boundary handling. IffromIndex is greater than the actual length, ortoIndex is less thanfromIndex, it usually returns an empty string or an empty list. IftoThe index is out of range, it will automatically truncate to the end of the string or list.This design avoids template rendering errors caused by index out of bounds, making our development more robust.