How to use `wordcount` to create dynamic styles based on content length in AnQiCMS template design?

Calendar 👁️ 71

In website content operation, we often encounter a challenge: how to keep the website interface beautiful and readable when displaying content of different lengths?A short news report and an in-depth industry analysis, they should be distinguished in terms of layout and style to provide a better user experience.AnQiCMS (AnQiCMS) fully understands this need and provides powerful and flexible tools in template design to solve this problem.Today, let's discuss how to use AnQiCMS'swordcountFilter, create a dynamic style based on the content length.

wordcountWhat is it? How does it work?

In the AnQiCMS template system,wordcountIt is a very practical filter, its main function is to calculate the number of "words" in a given string.The "word" is calculated based on the space-separated text fragments. When you willwordcountWhen applied to a content variable, it returns an integer representing the total number of words in the content.

For example, if you have a string"欢迎使用安企CMS,一个强大的内容管理系统"Pass it throughwordcountAfter filtering, a number will be obtained.

In simple terms, its usage is like this:

{{ "这是一个短句子"|wordcount }}

This code will output4.

Why should we use it in the templatewordcount?

UtilizewordcountFilter, we can implement various dynamic style requirements in the AnQiCMS template.Imagine that your website has both concise news and in-depth analysis long articles.By judging the number of words in the content, we can apply different CSS style classes to them, thus achieving visual distinction and layout optimization.

This not only enhances user experience, allowing users to identify the type of content at a glance, but also helps designers better control page elements, avoiding issues such as content overflow or excessive blank spaces. For example, we can decide based on the length of the content:

  • Does the article summary card show the 'Read More' button or adjust the size of the summary?
  • If the title in the list is too long, it can be automatically truncated or提示 with different colors.
  • The detail page of the article adjusts the width of the main content area according to the length of the article, and even changes the display of the sidebar.

The ability to dynamically adjust the display according to the content is exactly the embodiment of the flexibility of AnQiCMS templates.

Apply in AnQiCMS templatewordcountPractice

Implementing dynamic styles based on content length in the AnQiCMS template, the core lies in combiningwordcountfilter tags and conditional judgment tags (if/elif/else)。Below, we demonstrate its application through several specific scenarios.

1. Create dynamic styles and functions for the article summary card.

Assuming we have a list of articles, each article is displayed in card form, including the title, brief description, and link.We hope that the short summary is displayed directly, and the longer summary is truncated and a "Read More" button is provided.At the same time, apply different background colors to different-length summaries for distinction.

Firstly, we need to obtain a brief description of the article. In AnQiCMS, this is usuallyarchive.Descriptionfield.

{% archiveList archives with type="page" limit="10" %}
    {% for archive in archives %}
        {% set description_word_count = archive.Description|wordcount %}
        <div class="article-card {% if description_word_count < 30 %}card-short{% elif description_word_count < 80 %}card-medium{% else %}card-long{% endif %}">
            <h3><a href="{{ archive.Link }}">{{ archive.Title }}</a></h3>
            {% if description_word_count < 50 %}
                <p>{{ archive.Description }}</p>
            {% else %}
                <p>{{ archive.Description|truncatewords:45 }}...</p>
                <a href="{{ archive.Link }}" class="read-more-btn">阅读更多</a>
            {% endif %}
        </div>
    {% endfor %}
{% endarchiveList %}

In this code block:

  • We first pass througharchive.Description|wordcountGet the number of words in the description and store it indescription_word_countthe variable.
  • Next, according todescription_word_countvalue, dynamically add or removearticle-cardto the elementcard-short/card-mediumorcard-longThese CSS classes. These classes can be predefined in your stylesheet (CSS), for example, setting different background colors or border styles for cards of different lengths.
  • At the same time, we also determine the display method of the summary based on the word count: if the description is short (fewer than 50 words), it is displayed in full; otherwise, it is truncated and a "Read More" link is added at the end.

2. Adjust the title style based on title length

In some list or navigation areas, a long title may disrupt the layout. We can apply different font sizes or colors based on the length of the title.

{% archiveList archives with type="list" limit="5" %}
    {% for archive in archives %}
        {% set title_word_count = archive.Title|wordcount %}
        <li class="article-item">
            <a href="{{ archive.Link }}" class="{% if title_word_count > 8 %}title-condensed{% else %}title-normal{% endif %}">
                {{ archive.Title }}
            </a>
        </li>
    {% endfor %}
{% endarchiveList %}

Here, if the number of words in the title exceeds 8, it should be appliedtitle-condensedClass (for example, it can be defined in a smaller font or truncated with an ellipsis), otherwise applytitle-normalClass.

3. Dynamically adjust the layout of the content area

For the article detail page, if the article content is particularly long, we may wish for it to occupy a wider page, to reduce the number of scrolls and enhance the reading experience.On the contrary, short articles can maintain the standard width.

{% archiveDetail archiveContent with name="Content" %}
    {% set content_word_count = archiveContent|wordcount %}

    <div class="article-detail-wrapper {% if content_word_count > 800 %}layout-wide{% else %}layout-standard{% endif %}">
        <h1>{{ archive.Title }}</h1>
        <div class="article-metadata">
            <span>发布日期:{{ stampToDate(archive.CreatedTime, "2006-01-02") }}</span>
            <span>阅读量:{{ archive.Views }}</span>
        </div>
        <div class="article-body">
            {{ archiveContent|safe }} {# 确保HTML内容安全输出 #}
        </div>
    </div>
{% endarchiveDetail %}

In this example, we retrieve the number of words in the article content. If it exceeds 800 words, we add the article container withlayout-wideA class, to make it wider in CSS; otherwise, uselayout-standardstandard layout.

Tips and注意事项

  • **wordcount

Related articles

What is the result returned by the `wordcount` filter for an empty string or a string that only contains spaces?

The template engine of AnQiCMS (AnQiCMS) provides a series of practical filters to help us flexibly handle data on the front-end page.Among them, the `wordcount` filter is a tool used to count the number of words in a string, which is often used in content operation to ensure that articles meet specific word count requirements or for content analysis.When discussing the `wordcount` filter, a common question is: what kind of result will it return when it encounters an empty string or a string that only contains spaces?

2025-11-09

How to display the first or last word of a string in AnQiCMS template?

In website content operation, we often need to refine the control of displayed information.Sometimes, a title may be long, and we only want to display the first word in a specific area, or highlight the last word for some design needs.AnQiCMS (AnQiCMS) provides a powerful and flexible template engine, which draws on the essence of Django template syntax, allowing us to achieve these seemingly complex text processing requirements through simple filters (Filters).Today, let's talk about how to use the AnQiCMS template

2025-11-09

What effect will be produced when the `wordcount` filter is combined with the `add` filter?

AnQiCMS with its flexible and powerful template system makes the presentation and data processing of website content very efficient.In the process of template development, skillfully combining various filters often unlocks unexpected practical effects.Today, let's delve deeply into two seemingly basic filters that, when combined, can produce wonderful effects: `wordcount` and `add`.

2025-11-09

In AnQiCMS content management, after batch replacing keywords, will the `wordcount` result be automatically updated?

In content management, efficiency and accuracy are the core concerns of operators.AnQiCMS is a feature-rich CMS that provides various tools to simplify content maintenance.Among them, the batch keyword replacement function greatly improves the efficiency of content adjustment, while word count (`wordcount`) is an important indicator of content length.Around these two features, users often wonder: Will the word count automatically update after the content has been replaced with batch keywords?

2025-11-09

The `wordcount` filter can be nested with other logical judgments (such as `for` loops)?

AnQiCMS provides a flexible and powerful template engine, allowing us to build website content with ease.In daily content display and data processing, there are often scenarios where you need to count the length of text, such as displaying the number of words in the abstract of an article list, or limiting the length of user comments.At this time, the `wordcount` filter comes into play.Many friends may be curious, whether the `wordcount` filter in the AnQiCMS template, in addition to being applied directly to variables, can also be used with other logical judgment tags, especially

2025-11-09

How to use `wordcount` as a preliminary measure of content quality before publishing an article?

In content operation, publishing high-quality articles is the core to attract users and improve search engine rankings.AnQiCMS (AnQiCMS) provides rich features to help us manage and optimize content.Before publishing the article, using some preliminary indicators for inspection can effectively improve the quality of the content.Among them, word count (`wordcount`) is a simple yet practical preliminary measure.Why Word Count is So Important for Content Quality?The word count is not just a number; it plays a multiple role in content quality assessment: 1.

2025-11-09

How does the `wordcount` filter define words when processing strings containing non-ASCII characters (such as emojis)?

It is crucial to master the usage of various template filters when managing and presenting content in Anqi CMS, especially tools like `wordcount` that seem simple but may bring subtle differences.As our content becomes richer and no longer limited to pure text, the emergence of emojis and multilingual characters makes the definition of 'word' less intuitive.The `wordcount` filter in Anqi CMS, as the name implies, is used to count the number of words in a string.Its usage is very concise, whether it is directly applied to a variable, for example `{{

2025-11-09

How to display the total word count of all Tag tags in a document within AnQiCMS?

In the daily operation of AnQiCMS, we often need to analyze and optimize content in detail.For SEO and content strategy, it is a fundamental and practical requirement to understand the word count and word number of various elements in the document.Today, we will discuss a specific scenario: how to display the total word count of all associated Tag tags in an AnQiCMS document.This can not only help us better evaluate the quality and relevance of tags, but it can also be used in some specific content display needs.AnQiCMS provides a powerful and flexible template tag and filter mechanism

2025-11-09