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.