How to calculate the number of words in a string with the `wordcount` filter in Anqi CMS template?

Calendar 👁️ 68

When processing text content in the Anqi CMS template, we often need to perform various operations on strings, such as counting words, cutting content, and so on.Among them, calculating the number of words in a string is a common requirement, which is very useful in content analysis, SEO optimization, and even estimating the reading time of an article.A security CMS provides a concise and powerful tool——wordcountfilter.

wordcountFilter: Core Function and Role

wordcountThe filter is specifically used to count the number of words in a given string.It identifies words by recognizing spaces in strings and considers each sequence separated by spaces as a separate word.Finally, it will return an integer representing the total number of words counted.

This filter is very useful in the scenario where quantitative analysis of text is required.For example, you can quickly understand the overall length of an article, provide the user with an estimated content reading time, or use it as a word limit reference in some content submission scenarios.

UsewordcountFilter Calculation of Word Count

Using in Anqi CMS template,wordcountThe filter is very intuitive. You can apply it to strings in two main ways: by using it directly after a variable, or by combiningfilterlabel usage

1. Apply it directly to a variable or a fixed string

This is the most commonly used method, you just need towordcountAttach the filter to the string variable or direct string literal you want to count the number of words after, using the pipe symbol|to connect.

For example, if you want to count the number of words in the article title (archive.Title) or the article content (archive.Content):

<p>文章标题中的单词数量:{{ archive.Title | wordcount }}</p>
<p>文章内容中的单词数量:{{ archive.Content | wordcount }}</p>

You can also count the words of a fixed text string directly:

<p>“Hello AnqiCMS World”这句话的单词数量是:{{ "Hello AnqiCMS World" | wordcount }}</p>

The output of this code will be:“Hello AnqiCMS World”这句话的单词数量是:3

2. CoordinatefilterTag usage

When you need to perform word count on a complex string that contains multiple lines or is generated by other template tags, you can usefiltertags to wrap the content and thenwordcountThe filter is applied to the entire content block.

For example, combineloremThe tag generates random text and counts the number of words:

{% filter wordcount %}
    {% lorem 25 w %} {# 生成25个单词的随机文本 #}
{% endfilter %}

The output of this code will be:25(becauselorem 25 wGenerate exactly 25 words,wordcountThe filter will accurately count)

wordcountThe actual application scenarios of the filter

wordcountThe filter is not just a simple count, it can play a role in various content operation scenarios:

  • Estimate reading timeBy dividing the total number of words in an article by the average reading speed (for example, 200-300 words per minute), you can easily display the estimated reading time on the article page, enhancing user experience.
  • Content Length Control: When it is necessary to limit the length of user-generated content or specific content areas (such as summaries, descriptions),wordcountProvide a convenient real-time count to help users and operators follow the rules.
  • SEO and content quality analysisFor SEO purposes, search engines tend to index articles that are detailed and informative.wordcountCan assist content editors in checking whether the article has reached the target word count, in order to better elaborate on the theme.
  • A/B testing: When conducting A/B tests on the impact of different content lengths on user behavior,wordcountCan provide accurate quantitative data.

Precautions for use

While usingwordcountWhen filtering, there are several key points to note:

  1. Delimiter identification:wordcountThe filter defaults to usingspacesAs a separator of words. This means that a continuous string like 'AnqiCMSWebsite' is considered a single word, even if it may contain multiple meanings in semantics.
  2. Process non-English contentFor Chinese, Japanese, and other languages that do not use spaces to separate words,wordcountThe filter will also treatContinuous non-space character sequencesConsidered as a word. Therefore, a Chinese sentence without English spaces, even if it contains many Chinese characters, may be counted as one or a few words, which is different from our usual understanding of 'word count' or 'number of words'.If you need to count the Chinese characters, you may need to consider other methods or combine it with JavaScript on the front end.
  3. Return type:wordcountThe filter always returns an integer value.

wordcountThe filter is a small but powerful tool in the Anqi CMS template.Mastering its usage allows you to have more flexibility and data support in content presentation and management, thus better optimizing the user experience and content strategy of the website.


Frequently Asked Questions (FAQ)

  1. Q:wordcountCan the filter count the number of characters in a Chinese paragraph? A: wordcountThe filter mainly based onspacesTo separate and count words. For Chinese paragraphs, since there are usually no spaces between words, it will treat a continuous Chinese text as one or a few words (depending on the presence of English punctuation or numbers and the like).Therefore, itNot suitableDirectly used for counting the Chinese 'word count' or the exact 'word number'. If you need to count the actual number of Chinese characters, you may need to combine other methods.

  2. Q:wordcountandlengthWhat are the differences between filters? A:They count different objects.wordcountThe filter counts the characters in a string.The number of words separated by spaces.Returns an integer.lengthThe filter counts the string's characters.Character countFor English characters, one letter counts as one character; for Chinese characters, one character counts as one character (AnQi CMS is processed based on UTF-8). In short,wordcountFocus on "word",lengthFocus on "character" or "symbol".

  3. Q: Can I usewordcountDo you have a filter to calculate the estimated reading time of an article? A:Yes. First, you can usewordcountThe filter retrieves the total number of words in the article content. Then, you can combine it with a preset average reading speed (for example, 200-300 words per minute) through simple mathematical operations to estimate the expected reading time. For example,{{ (archive.Content | wordcount) / 250 }}You can estimate the approximate number of minutes, and you can round it up or down as needed.

Related articles

How `urlize` and `urlizetrunc` filters automatically convert URLs and email addresses in text to clickable hyperlinks?

How to efficiently and beautifully convert text containing URLs and email addresses into clickable hyperlinks when managing website content in AnQi CMS, is a concern for many content operators.Manually adding the `<a>` tag to each URL or email is not only time-consuming and labor-intensive but also prone to errors.Luckily, AnQi CMS provides two very practical template filters——`urlize` and `urlizetrunc`, which can automatically complete this task and greatly improve the efficiency and user experience of content publishing.### `urlize`

2025-11-08

What are the differences between the `urlencode` and `iriencode` filters in URL parameter encoding, and which scenarios are they applicable to?

In website operation, the construction and processing of URL (Uniform Resource Locator) is a fundamental and critical task.It is crucial to properly encode URLs when dynamically generating links, handling user input as parameters, as it ensures the validity of the links, prevents garbled text, and potential security issues.AnQiCMS provides the `urlencode` and `iriencode` filters to help us better manage special characters in URLs.Although they are all used for encoding, their application scenarios and processing methods are different.

2025-11-08

How to safely truncate text with HTML tags using `truncatechars_html` and `truncatewords_html` filters to prevent structure damage?

In website content operation, we often need to display the summary or part of the content in different scenarios, such as on the list page, search results, or related recommendations.This is when you need to truncate the content.If the content is plain text, a simple character or word cutter can handle the task well.However, when the content is rich in HTML tags, the problem becomes complex: directly cutting may cause the HTML tags to be truncated, thereby destroying the page structure, causing display errors, and even affecting the user experience.

2025-11-08

How to handle truncation and add an ellipsis when truncating text with `truncatechars` and `truncatewords` filters, including HTML content?

In the increasingly fragmented information consumption era, the way websites present content directly affects user experience.Whether it is the abstract of an article list, the preview of product introduction, or various information stream cards, we need to convey the core information within a limited space while maintaining the page's neatness and uniformity of layout.This introduces the need for text truncation. AnQiCMS, as a fully functional content management system, understands this well and provides us with a powerful text truncation filter, especially its intelligent processing capabilities for HTML content, making content operations more relaxed.

2025-11-08

How does the `wordwrap` filter automatically wrap long text to a specified length

In the daily operation of websites, we often encounter such situations: the content of the article is too long, or the text extracted from other places has not been formatted, resulting in the text content exceeding the container width when displayed on the web page, destroying the overall layout and seriously affecting the reading experience of users.Especially on mobile devices, long lines of text are more difficult to read.To solve this problem, Anqi CMS provides a very practical tool - the `wordwrap` filter, which can help us automatically wrap long text to the specified length, thereby optimizing the display effect of the content

2025-11-08

How does AnQiCMS ensure that website content displays perfectly on different devices?

In the digital age, website content can seamlessly adapt to various devices, from large desktop monitors to small smartphone screens, and is no longer an option, but the cornerstone of success.The user expects to have a smooth, beautiful, and fully functional experience regardless of which device is accessed.AnQiCMS as a product designed for efficient content management, provides a series of powerful and flexible features to ensure that your website displays content perfectly on any screen, making it shine on any screen.### AnQiCMS's multi-dimensional adaptive strategy AnQiCMS

2025-11-08

How to manage and present the content of multiple independent brand websites in AnQiCMS in a unified manner?

In the current digital age, the need for enterprises or content operators to manage multiple independent brand websites is increasingly common.Each brand may have a unique style, product line, or target audience, but how to efficiently manage these contents under a unified framework, achieve centralized display under specific scenarios, while maintaining the independence of each brand, is a challenge faced by many teams.AnQiCMS as an enterprise-level content management system, its multi-site management function provides a powerful solution for this.One of the design初衷 of AnQiCMS is to serve users with multi-site management needs

2025-11-08

How to flexibly display different content types on the front-end page after customizing the content model?

In modern website operations, the diversity and personalized display of content is the key to attracting users and enhancing brand image.AnQiCMS (AnQiCMS) with its flexible content model design, brings unprecedented freedom to website content management.How to elegantly present the content with unique structure on the front page after we customize the content model according to business requirements, is a core skill that every operator needs to master.

2025-11-08