AnQiCMS provides a flexible and powerful template engine, allowing us to be at ease when building website content.In daily content display and data processing, we often encounter scenarios where we need to calculate the length of text, such as displaying the word count of abstracts in article lists, or limiting the length of user comments, etc.Now, wordcountThe filter comes into play.

Many friends may be curious,wordcountCan the filter in the AnQiCMS template, in addition to being applied directly to variables, also be used with other logical judgment tags, especiallyforDoes such a loop traverse label nesting work? The answer is yes, and this combination can greatly enhance the flexibility and practicality of the template.

wordcountBasic usage of filters review

Before delving into nested usage, let's take a brief review.wordcountThere are two basic ways of using filters.

The first is to apply it directly to a variable and count the number of words in its content. For example, if we want to get the number of words in an article title, we can write it like this:

{{ archive.Title|wordcount }}

This method is very intuitive and suitable for quickly counting a single variable.

The second one is used as a block-level filter, which counts the total number of words within its enclosed content.This is especially suitable for counting the number of words in complex content composed of multiple variables or static text.For example, combineloremTags generate random text and count:

{% filter wordcount %}{% lorem 25 w %}{% endfilter %}

here,wordcountFiltering acts on{% lorem 25 w %}The generated text and output the total number of words.

wordcountthe filter meetsforThe combination of practice

Now, let's take a lookwordcountHow to combine the filter withforNested use of this kind of logical tag in the loop, which is the embodiment of the powerful features of the AnQiCMS template.

1. AtforUse directly inside the loopwordcountFilter

This is the most common combination. When traversing a data list, we may need to count the number of characters in a certain field of each item in the list.wordcountThe filter can be applied to each element within the loopitemthe variable.

Suppose we have a list of articles.archivesWe want to display the title and description of each article in the list, as well as the number of words in the description. We can write the template like this:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li>
        <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
        <p>{{item.Description}}</p>
        <span>描述字数:{{ item.Description|wordcount }}</span>
    </li>
    {% empty %}
    <li>暂无文章内容</li>
    {% endfor %}
{% endarchiveList %}

In this example,{{ item.Description|wordcount }}Placed inforInside the loop, each loop iteration will process the current article'sDescriptionThe field performs independent word statistics and outputs the results. This usage is very natural and meets our expectations for data traversal and processing.

2. Inforwithin a loop{% filter wordcount %}block

When the content to be counted is dynamically combined from multiple parts inside the loop, block levelwordcountThe filter is particularly flexible. For example, we may need to count the total number of characters in the combination of each article's title and brief description (such as the first 20 characters).

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li>
        <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
        {% filter wordcount %}
            {{ item.Title }} - {{ item.Description|truncatechars:20 }}
        {% endfilter %}
        <span> 个单词</span>
    </li>
    {% empty %}
    <li>暂无文章内容</li>
    {% endfor %}
{% endarchiveList %}

here,{% filter wordcount %}wrapped in block{{ item.Title }}and{{ item.Description|truncatechars:20 }}The output. In everyforthe loop,wordcountThe filter first retrieves the rendered text content of these two variables, then performs word statistics on their combined text. This perfectly demonstrates the block-level filter inforNested loops are used to count the number of characters in dynamically generated content.

3. In{% filter wordcount %}Nested within a block.forLoop

Although this scenario is relatively rare, the AnQiCMS template engine also allows us tofornested loops in{% filter wordcount %}such a block-level filter. In this case,wordcountthe filter will takeforLoopAll iterative output resultsTreated as a whole string, then count the number of words in the whole string.

For example, we want to count the total number of characters in the titles of all articles under a certain category, not just the number of characters in the title of a single article:

{% set categoryId = 1 %} {# 假设要统计分类ID为1的文章 #}
<p>分类ID为 {{ categoryId }} 的所有文章标题总字数:</p>
{% filter wordcount %}
    {% archiveList archives with type="list" categoryId=categoryId limit="all" %} {# limit="all"获取所有文章 #}
        {% for item in archives %}
            {{ item.Title }}
        {% endfor %}
    {% endarchiveList %}
{% endfilter %}
<span> 个单词。</span>

In this example,forThe loop traversed all article titles under the specified category and concatenated them (by default, there will be spaces or line breaks depending on the template output), and then the outermost layer{% filter wordcount %}The block will count the total number of words in all these title texts. This usage is very useful when you need to perform a statistical analysis on a specific aggregate text in the entire dataset.

Summary and **practice**

It can be seen from the above example that the AnQiCMS template containswordcountthe filter meetsforLoop and logical judgment tags can be flexibly nested.No matter if you want to count individual elements in a loop, or count the dynamic combination of content in a loop, or even count the aggregated content of the entire loop output, AnQiCMS provides the corresponding support.

When using these advanced features, it is recommended to maintain clear and readable template code, avoid overly complex nesting, to ensure the convenience of subsequent maintenance. At the same time, please notewordcountThe filter counts the number of "words", it uses spaces, punctuation marks, and other delimiters to judge words. For Chinese characters, AnQiCMS'slengthThe filter counts a Chinese character as 1 character when calculating the length of a string, andwordcountThe filter also counts each Chinese character individually, as it treats continuous Chinese character strings without spaces as a single word.

By mastering the combination of these template tags and filters, you will be able to build a feature-rich AnQiCMS website more efficiently and flexibly.

Frequently Asked Questions (FAQ)

1.wordcountCan the filter accurately count the number of Chinese characters? wordcountThe filter is mainly based on spaces and punctuation marks to distinguish 'words'.For continuous Chinese character strings, even without spaces, they are counted as a whole and not counted one by one for individual characters.If you need to accurately count the number of Chinese characters (one character counts as one), it is recommended to uselengthFilter, for example{{ item.Description|length }}.

2.wordcountCan the filter be used in a chain with other filters?Yes, AnQiCMS template engine supports chained filter usage. This means you canwordcountFilters combined with other filters (for examplelower/truncatecharssuch as) to achieve more complex data processing logic. For example:{{ item.Content|lower|wordcount }}It will first convert the content to lowercase and then count the number of words.

3. IfforThere is no data in the loop,wordcountWill the filter throw an error?will not. IfforThe data source being traversed by the loop is empty, orwordcountThe target variable applied by the filter is an empty string ornilIt will safely return 0 or an empty value without causing template rendering errors. You can combine{% empty %}tags to handleforlooping over no data to provide friendly prompts.