How to use the `wordcount` result in AnQiCMS for conditional judgment, such as displaying different prompts based on the word count?

Calendar 81

In AnQi CMS, implementing dynamic content display is an important aspect for improving user experience and website professionalism.Sometimes, we may want to display different prompts based on the length of the article content, such as prompting 'Quick Read' for short articles, while estimating reading time for long content.The powerful template engine and built-in filters of AnQi CMS make everything easy.

This article will deeply explore how to巧妙ly use in AnQiCMSwordcountThe filter combined with conditional judgment, realizes the dynamic prompt function based on the number of characters (words) in the content.


UnderstandingwordcountThe role of the filter

In the AnQiCMS template system,wordcountIt is a very practical filter, as the name implies, its main function is to count the number of words in a given string. According to the system documentation,wordcountCalculate words with space as separator and return an integer value.This means that, whether it is an English article or a Chinese phrase separated by spaces, it can give the corresponding number of "words".

For example, if we have a content variablearchiveContentto get the word count of it, we can use it like this:{{ archiveContent|wordcount }}This line of code will directly outputarchiveContentthe total number of words contained.

Why do we need to make conditional judgments based on the number of words?

In the operation of actual websites, the length of the content often determines the user's reading expectations and our strategy for providing auxiliary information.

  • Improve user experience:For short content, we can directly prompt users to quickly browse, reducing their reading pressure; for long content, we can estimate reading time to help users arrange their time appropriately.
  • Optimize SEO strategy:Sometimes, search engines evaluate page quality based on the richness of the content.For articles that are too short, you can display a prompt to encourage the author to expand the content, or guide users to access more related articles.
  • Differentiation display:On the list page, display different "Read More" button styles based on the length of the article abstract, or add an "Expand" feature for particularly long abstracts.

BywordcountCombine conditional judgment, we can implement these refined content operation strategies.

towordcountThe result is used for conditional judgment

AnQiCMS template engine supports conditional judgments similar to Django syntax, mainly through{% if ... %}tags. We can usewordcountThe result of the filter, stored in a variable, and then various logical judgments are made on this variable.

Firstly, we need to obtain the content to be counted. Usually, this will be in the article detail page ofarchive.Contentor the list page ofarchive.Description(Document summary).

Suppose we want to count the words in the article detail page ofdetail.htmlIn the template, based on the article contentarchive.ContentDifferent prompts are displayed according to the number of words. We can do this:

Step 1: Get the article content and calculate the number of words

{%- archiveDetail articleContent with name="Content" -%} {# 获取文章内容 #}
{%- set contentWordCount = articleContent|wordcount -%} {# 将单词数量存储在 contentWordCount 变量中 #}

This has been used-Characters to remove blank lines that may be generated by template tags, making the code cleaner.

Step two: Set conditional judgment and prompt information based on the number of words.

Now, we havecontentWordCountThis variable can be used{% if %}/{% elif %}and{% else %}to judge.

{%- archiveDetail articleContent with name="Content" -%}
{%- set contentWordCount = articleContent|wordcount -%}

<div class="content-tips">
    {% if contentWordCount < 100 %}
        <p>💡 这篇文章内容精炼,预计只需1分钟即可快速阅读完毕!</p>
    {% elif contentWordCount >= 100 and contentWordCount < 500 %}
        <p>🕒 预计阅读时间约3分钟,为您快速了解主题提供帮助。</p>
    {% else %}
        <p>📚 这是一篇深度好文,预计阅读时间较长,请您静心品读。</p>
    {% endif %}
</div>

<div class="article-content">
    {{ articleContent|safe }} {# 输出文章内容,注意使用safe过滤器 #}
</div>

In this example:

  • If the number of words in the article is less than 100, a 'Quick Read' prompt will be displayed.
  • If the number of words is between 100 and 499 (inclusive), a "approximately 3-minute reading" prompt will be displayed.
  • If the word count reaches or exceeds 500, a prompt 'A deep good article, please read with calmness' will be displayed.

More practical scenario examples

1. Dynamic prompt of the article summary on the list page

On the article list page, we may want to adjust the display based on the length of each article summary.

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <div class="article-card">
        <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
        {%- set descriptionWordCount = item.Description|wordcount -%}
        <p class="description-text">
            {{item.Description}}
            {% if descriptionWordCount > 80 %}
                <span class="read-more-hint">... (摘要较长,建议点击查看详情)</span>
            {% else %}
                <span class="read-more-hint">... (了解更多)</span>
            {% endif %}
        </p>
        <a href="{{item.Link}}" class="read-more-btn">继续阅读</a>
    </div>
    {% endfor %}
{% endarchiveList %}

This example shows that if the number of words in the summary exceeds 80, a more specific reading prompt will be displayed.

2. SEO suggestions based on content length.

Although this is usually the responsibility of the backend or editor, it can also provide friendly hints at the template level.

{%- archiveDetail articleContent with name="Content" -%}
{%- set contentWordCount = articleContent|wordcount -%}

{% if contentWordCount < 300 %}
    <div class="seo-alert">
        <p>⚠️ 注意:文章内容字数较少(当前{{ contentWordCount }}词),可能不利于搜索引擎收录和排名,建议扩充内容。</p>
    </div>
{% endif %}

<div class="article-content">
    {{ articleContent|safe }}
</div>

**Practice and Precautions

  • Code neatness:Although it can be done directly inifcondition calculationwordcountbut using{% set %}Store the result in a temporary variable, which can make the template code clearer and more readable, especially when you need to refer to this value multiple times.
  • Calculation base: wordcountThe number of words separated by spaces. For pure Chinese content without spaces,wordcountit may return 1. If you need the exact number of characters, consider usinglengthfor example, a filter (such as{{ archiveContent|length }}),and adjust the judgment threshold according to actual needs.
  • Performance consideration: The logic within the template should be as concise as possible.wordcountThe filter itself is very efficient, but when performing frequent calculations on extremely complex loops or large amounts of content, one should be aware of the potential performance impact.For the vast majority of websites, this is usually not a problem.
  • User Experience:The prompt information should be natural and friendly, without interfering with the user's reading. The use of colors should also conform to the overall style of the website.

By using the above method, you can implement flexible and diverse conditional judgments and dynamic prompts in AnQiCMS based on the word count of the content, making the website content more interactive and intelligent, thereby effectively improving user experience and content operation efficiency.


Frequently Asked Questions (FAQ)

Q1:wordcountThe filter counts words or characters?

A1:wordcountThe filter is mainly used to count the number of words in a string. It separates the string based on spaces and treats each separated part as a word.For example, "AnQiCMS is great" will be counted as 3 words.“AnQi CMS is great” If there is no space, it will be counted as 1 word.If you need to count the number of characters, you can uselengthfilter.

Q2: If I want to judge based on the number of characters in the content, which filter should I use?

A2: If you need to judge based on the character count of the content, you can use the AnQiCMS providedlengthA filter. It returns the actual character count of a string, including Chinese, English, symbols, etc. For example,{% set charCount = articleContent|length %}you can get the character count, and then you can{% if charCount > 200 %}Judging under such conditions.

Q3: Can I judge the summary of each article in the loop on the article list page?wordcountWill it affect performance?

A3: Yes, you can loop through the article list page's{% for item in archives %}and judge the summary(item.Description)wordcountfor example.{% set descWords = item.Description|wordcount %}.For general websites, this operation has a negligible impact on performance, becausewordcountThe filter itself has a high efficiency. However, if your list contains tens of thousands of articles and executes a large amount of complex template logic in a loop, it may slightly increase the page rendering time.In most cases, there is no need to worry too much.

Related articles

Can I use the `wordcount` filter to check if the user's submitted content meets the minimum word count requirement?

In the daily content operation of AnQiCMS (AnQiCMS), we often encounter the need to limit the number of words or characters in user-submitted content to ensure the quality and standardization of the content.So, can the `wordcount` filter provided by Anqi CMS help us achieve this goal?This article will delve into the functionality, usage, and application of the `wordcount` filter in content management, and point out its limitations, helping you better utilize this tool.

2025-11-09

What is the core difference between the `wordcount` filter and the `length` filter in calculating text length?

In AnQi CMS template development, we often need to process and count text content, including calculating the length of the text.The system provides the `wordcount` and `length` filters, which both help us measure text, but they have different focuses and application scenarios.Understanding the core differences can make us more proficient in practical use, writing more efficient and accurate template code.

2025-11-09

AnQiCMS blog article detail page, how to display the total word count of the current article in real time?

In content operation, the word count (or number of words) of an article is often an important indicator for measuring the depth of content, the estimated reading time, and even search engine optimization (SEO).For those of us who use AnQiCMS to manage website content, being able to display the total word count of the current article in real-time on the blog article detail page would undoubtedly enhance user experience and provide more intuitive data reference for website operation.AnQiCMS powerful template system and built-in features make it simple and efficient to meet this requirement.

2025-11-09

How to use the `wordcount` filter to display the word count of each article on the article list page?

When operating a website, we often need to understand some basic information about articles, such as reading time, word count, etc.This data not only helps us optimize the content strategy, but also allows readers to have a preliminary judgment of the article while browsing.In Anqi CMS, by using its powerful template filter function, we can easily display the word count of each article on the article list page.

2025-11-09

How does the `wordcount` filter handle strings containing numbers and special characters when counting?

AnQiCMS provides a series of practical and powerful template filters to help us process content.Among them, the `wordcount` filter is a commonly used one in content operation, which aims to count the number of 'words' in a string.However, when our string contains numbers, special characters, or even Chinese characters, how does `wordcount` actually count?This is the place where many users may feel confused when using it, and we will discuss its internal logic in detail next.

2025-11-09

In AnQiCMS template, how to ensure that the `wordcount` filter removes HTML tags before counting?

When processing content in the AnQiCMS template, we often need to perform various operations, such as counting the number of words in an article.The word count is a very basic but practical function for content management, which helps us assess the richness of content and is also an important reference indicator for SEO optimization.AnQiCMS built-in `wordcount` filter provides great convenience for this, allowing us to easily obtain the word count of text.

2025-11-09

How to avoid extra whitespace characters affecting the accuracy of word count when using `wordcount`?

In content operation, accurately counting the number of words in an article is crucial for SEO optimization, content length control, and even fee calculation.The Anqi CMS provides a convenient `wordcount` filter, which helps us quickly achieve this goal.However, if the content is not properly processed, extraneous whitespace characters may subtly affect the accuracy of counting.This article will delve into how to effectively avoid the interference of these blank characters when using the `wordcount` filter in Anqi CMS, ensuring you get the most accurate word count results.

2025-11-09

What are the different application scenarios between the `truncatewords` filter and the `wordcount` filter in text processing?

In AnQi CMS, we often need to flexibly handle text to adapt to different display requirements and information communication purposes.Among them, the `truncatewords` and `wordcount` filters are two powerful tools in the hands of content operators.They all seem to be related to 'word count' or 'words', but their actual application scenarios and focuses are quite different.Understanding the differences can help us optimize the presentation of website content more accurately.

2025-11-09