How to count the number of times a certain keyword appears in the article content in the AnQiCMS template?

Calendar 👁️ 60

In content operation, understanding the frequency of keyword appearance in articles is an important aspect for SEO optimization and content strategy analysis.By counting the number of keywords, we can better evaluate the density, relevance, and even identify potential optimization space of the content.AnQiCMS provides a powerful and flexible template system,配合 its built-in content filter, we can easily count the occurrences of specific keywords in the article content.

Understanding the requirement: Why do we need to count keywords?

Count the number of times a keyword appears in an article, and there are several practical application scenarios:

  1. SEO optimization evaluation: The search engine considers the frequency of keywords when determining the relevance of an article.Although 'keyword density' is no longer the only ranking factor, understanding its distribution still helps with content strategy.
  2. Content quality analysisThe frequency of keywords that is too high or too low may affect the reading experience. Moderate statistics can help us maintain the natural fluidity of the content and avoid keyword stacking.
  3. Internal link strategyIn some automated internal link tools, counting keywords helps identify which words can be converted into links, pointing to other related pages.
  4. Competitive analysisAnalyze the keyword frequency in competitors' articles to provide reference for your own content creation.

Core tool in AnQiCMS template: Content Filter

AnQiCMS's template syntax is flexible and powerful, drawing on the advantages of template engines like Django or Blade, supporting basic operations such as variables, conditional judgments, loops, and so on.What is more important is that it provides a rich set of content filters (Filters) that can perform various processing on the output data, such as formatting time, truncating strings, even counting characters or word numbers.To count the frequency of keywords, we mainly use two key points: obtaining the article content, and applying the statistical filter.

Get article content:archiveDetailTag

Firstly, we need to obtain the full content of the article in the template. In the AnQiCMS article detail page template, various data of the current article can usually be accessed directly througharchive.字段名Access in the form. The main content field of the article is usuallyarchive.Content.

If you need to get the content of a specified article on a non-article detail page (such as the homepage or list page), you can usearchiveDetailLabel. However, for our current needs - to count keywords in the "article content", it usually means we are on the article detail page, and we can directly usearchive.Contentis the most convenient way.

For example, inarchive/detail.htmlIn such an article detail template, we can directly access:

{{ archive.Content|safe }}

Here|safeThe filter is to ensure that the HTML tags in the article content are parsed and displayed correctly, rather than as plain text output.

Count the number of keywords:countFilter

Having the article content, the next step is to count the frequency of keywords. AnQiCMS provides a very practicalcountThe filter to accomplish this task. This filter can calculate the frequency of a keyword in a string.

countThe basic usage of the filter is as follows:

{{ obj|count:关键词 }}

Among them:

  • objThe string object we need to count, for examplearchive.Content.
  • 关键词The target string we need to count.

For example, if we want to count how many times the word 'CMS' appears in a text:

{% set text = "欢迎使用安企CMS(AnQiCMS),这是一个基于Go语言的CMS。" %}
{% set cms_count = text|count:"CMS" %}
<p>关键词 "CMS" 在文本中出现了:{{ cms_count }} 次。</p>

The output of this code will be:关键词 "CMS" 在文本中出现了:2 次。

Combine them to get the complete implementation steps:

Now, we combine obtaining the article content with usingcountthe filter steps together. Suppose we are editing a template for an article detail page (for example/template/default/archive/detail.htmlOr customize the article template) and you want to count the number of times a keyword appears in the current article content.

You can follow these steps:

  1. Define the keyword to be counted: For easy management and modification, we can first usesetTag to define a variable to store the keywords we want to count.
  2. Get article contentUtilizearchive.ContentGet the full content of the current article.
  3. applycountFilter:Input the article content as a filter, the keywords as parameters, and get the statistical results.
  4. Display the results:Display the statistical results on the page.

Here is a complete code example showing how to count the occurrences of the keyword "AnQiCMS" in the current article content in the AnQiCMS template:

{# 1. 定义要统计的关键词 #}
{% set keyword_to_count = "AnQiCMS" %}

{# 2. 检查文章内容是否存在,以避免不必要的错误 #}
{% if archive.Content %}
    {# 3. 对文章内容应用 'count' 过滤器进行关键词统计 #}
    {% set count_result = archive.Content|count:keyword_to_count %}

    {# 4. 在页面上展示统计结果 #}
    <div class="keyword-stats">
        <p>关键词 "{{ keyword_to_count }}" 在本文中出现了:<strong>{{ count_result }}</strong> 次。</p>
    </div>
{% else %}
    <div class="keyword-stats">
        <p>文章内容为空,无法统计关键词出现次数。</p>
    </div>
{% endif %}

Insert this code snippet into an appropriate location in your article detail template, such as below the article title, at the end of the body, or in the sidebar. The page will automatically calculate and display the number of times the keyword appears when it loads.

Practice Exercise: A Specific Example

We have an article about the 'AnQiCMS tutorial', which mentions 'AnQiCMS' and 'Go language' multiple times.We hope to display the statistics of these two keywords at the bottom of the article.

`twig {# This is a part of the article detail page template #}

<h1>{{ archive.Title }}</h1>
<div class="article-meta">
    发布日期: {{ stampToDate(archive.CreatedTime, "2006-01-02") }} | 浏览量: {{ archive.Views }}
</div>

<div class="article-content">
    {{ archive.Content|safe }}
</div>

<div class="keyword-analysis">
    <h3>关键词统计分析:</h3>
    {% set keywords_to_analyze = ["AnQiCMS", "Go语言", "模板"]|list %} {# 定义一个关键词列表 #}
    {% set

Related articles

How to determine if a string or array in the AnQiCMS template contains a specific keyword?

In Anqi CMS template development and daily content operation, we often encounter the need to dynamically display information based on specific attributes or keywords of the content.To achieve personalized content recommendation, emphasize the specific theme of an article, or control the display of page elements based on certain indicators in the data, accurately determining whether a string or array contains specific keywords is a very practical skill.The Anqi CMS template system adopts a syntax similar to the Django template engine, built-in with rich filters and tags, which can help us easily implement such judgments. Next

2025-11-08

How to achieve text centering or left-right alignment formatting in templates for AnQiCMS?

In web design, the layout and alignment of content are key elements of user experience.No matter if you want to center the title or align the paragraph text to the left, AnQiCMS provides a flexible template mechanism, combined with standard Web technology, which can easily meet these needs.AnQiCMS as a content management system developed based on the Go language has its core advantages in providing efficient, customizable content management and data output.It uses a syntax similar to the Django template engine, allowing you to combine system data (such as article titles, content, etc.) with

2025-11-08

How to automatically capitalize the first letter of an article title, or to achieve full uppercase/lowercase conversion?

In content operation, a standardized and unified title format is crucial for the brand image of the website and the user reading experience.To enhance visual tidiness or to meet specific design styles, automatically adjusting the case of the article title is a very practical feature.AnQiCMS as a flexible content management system, provides a convenient way to help us achieve this goal without complex programming, and it can be easily handled.

2025-11-08

How to correctly escape special characters in the AnQiCMS template to avoid display errors?

In website content management, we often need to display text containing various special characters.If these special characters are not handled correctly, it may lead to page layout chaos, functional anomalies, and even security vulnerabilities.AnQiCMS provides a powerful mechanism to help us handle these special characters during template rendering, ensuring the correct display of content and the security of the website.

2025-11-08

How to remove specific characters or extra spaces from AnQiCMS template variables?

In website content operations, we often encounter such situations: the template variable content retrieved from the database may contain some unnecessary characters, extra spaces, or formats that are not satisfactory.These subtle details, if not handled properly, may affect the aesthetics of the page, user experience, and even cause interference with search engine optimization (SEO).AnQiCMS provides powerful template filtering functionality, helping us easily clean and format these variables.The template syntax of AnQiCMS is similar to Django engine

2025-11-08

How to format Unix timestamp into a readable date and time format in AnQiCMS template?

In website content management, time information plays a crucial role, whether it is the publication date of articles, update time, or the submission time of comments, the record of time is indispensable.Databases usually store these time data in a concise and efficient format - Unix timestamps.However, for the end user, a string of numbers in a timestamp is not as intuitive and easy to understand as “October 27, 2023 14:30”.

2025-11-08

What are the differences and applicable scenarios between the `default` and `default_if_none` filters when the template variable is empty?

In AnQi CMS template design, reasonably handling variables that may be empty is the key to ensuring the integrity and smooth user experience of website content display.When a template variable has no value or is in an 'empty' state, we usually do not want blank or error messages to appear on the page, but rather we would like to display a preset default content.At this time, the `default` and `default_if_none` filters provided by Anqicms come into play.They can all provide default values for variables

2025-11-08

In AnQiCMS template, how to determine if one number can be evenly divided by another to achieve conditional display?

In Anqi CMS template development, we often need to display content based on specific conditions, such as adding a special style to every few elements in a list or inserting separators at specific positions.When this condition is to determine whether a number can be divided by another number, Anqi CMS provides a concise and efficient solution with its powerful template engine.The Anqi CMS template system uses a syntax similar to the Django template engine, which makes it very intuitive in handling such logical judgments.To determine if a number can be evenly divided by another number

2025-11-08