AnQiCMS provides a flexible and powerful template engine, allowing us to handle website content construction with ease.In daily content display and data processing, it is often necessary to count the length of text, such as displaying the word count of abstracts in article lists, or limiting the length of user comments, etc.wordcountThe filter comes into play.
Many friends may be curious,wordcountIn AnQiCMS templates, besides being applied directly to variables, can the filter be used with other logical judgment tags, especiallyforDoes the loop traverse such tags nested? The answer is affirmative, and this combination method can greatly enhance the flexibility and practicality of the template.
wordcount过滤器的基础用法回顾
Before delving into nested usage, let's briefly review.wordcountThe two basic ways of using filters.
The first is to apply it directly to a variable, to count the number of words in the variable content. For example, if we want to get the word count of 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 is used as a block-level filter, which counts the total number of words in the content it wraps.This is particularly suitable for counting the number of words in complex content composed of multiple variables or static text.loremThe label generates random text and counts:
{% filter wordcount %}{% lorem 25 w %}{% endfilter %}
Here,wordcountFilter affects{% lorem 25 w %}The generated text, and outputs the total number of words.
wordcountFilter is related toforCombining practice in loops
Now, let's take a look atwordcounthow the filter interacts withfornested usage of logic tags like loops, which is a manifestation of the strength of AnQiCMS templates.
1. Inforusing directly within the loopwordcountFilter
This is the most common combination. When traversing a data list, we may need to perform word count on a certain field of each item in the list.wordcountFilter can be applied to each item within the loopitemfilter to the variable.
Assume we have a list of articlesarchivesWe want to display the title and description of each article in the list, and also show the word count of 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 inforWithin the loop, each iteration will process the current article'sDescriptionField performs independent word statistics and outputs the results. This usage is very natural and conforms to our expectations of data traversal and processing.
2. Infornested within a loop{% filter wordcount %}Block
When the content to be counted is dynamically composed of multiple parts within a 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 a brief description (for example, 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 %}Block wrapped.{{ item.Title }}and{{ item.Description|truncatechars:20 }}The output. In each timeforin the loop,wordcountThe filter will first get the rendered text content of these two variables, then perform word statistics on their combined text. This perfectly demonstrates the block-level filter inforLooping with nested usage, it implements word counting for dynamically generated content.
3. In{% filter wordcount %}Nested within a blockforLoop
Although this scenario is relatively rare, the template engine of AnQiCMS also allows us tofornested in a loop{% filter wordcount %}inside such block-level filters. In this case,wordcountthe filter willforLoopAll iterative output resultsConsidered as a whole string, then count the number of words in this 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,forCycled through all the article titles under the specified category, and concatenated them (default will have spaces or new lines, depending on the template output), and then the outermost layer of{% filter wordcount %}This block will count the total number of words in all the title texts. This usage is very useful when you need to count the aggregation text of a dataset.
Summary and **Practice
It can be seen from the above example that the templates in AnQiCMS contain,wordcountFilter is related toforLoops and logical judgment tags can be used flexibly nested.No matter if you want to count a single element in a loop, count dynamic content combined in a loop, or 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 pay attentionwordcountThe filter statistics the number of 'words', it uses spaces, punctuation marks, and other separators to judge words. For Chinese characters, AnQiCMS'slengthThe filter counts a Chinese character as 1 character when calculating the length of a string, andwordcountFilter also counts individual Chinese characters as words, as it considers a continuous string of Chinese characters without spaces as a single word.
By proficiently mastering the combination of these template tags and filters, you will be able to build a feature-rich AnQiCMS website more efficiently and flexibly.
Common Questions (FAQ)
1.wordcountCan the filter accurately count the number of Chinese characters?
wordcountThe filter is mainly based on spaces and punctuation to distinguish 'words'.For continuous Chinese character strings, even if there are no spaces, they are counted as a whole and not counted one by one as individual characters.lengthFilter, for example{{ item.Description|length }}.
2.wordcountCan the filter be used in a chain with other filters?Yes, AnQiCMS template engine supports the chained use of filters. This means you canwordcountfilters with other filters (such aslower/truncatecharsCombine with (等)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,wordcountDoes the filter report an error?No.forThe data source for loop iteration is empty, orwordcountThe target variable for filter application is an empty string ornilIt will safely return 0 or an empty value without causing template rendering errors. You can combine{% empty %}tags to handleforthe case of no data in loops, providing a friendly prompt.