How to efficiently check if a long string or array contains a certain keyword in the AnQiCMS template?

Calendar 👁️ 89

In the daily operation of AnQiCMS, we often need to quickly and accurately judge whether a specific keyword or phrase exists in the dynamic content of the website, such as the main body of articles, product descriptions, custom fields, even tag lists and category names.This need is especially common in content management, SEO optimization, or personalized display.How can you efficiently complete this task in the flexible and powerful template system of AnQiCMS?

AnQiCMS is developed based on the Go language, its template engine syntax is similar to Django templates, providing rich tags and filters, making it intuitive and efficient to handle such logic in front-end templates.The essence lies in fully utilizing the built-in filters provided by the system, simplifying complex judgment logic into a single line of code.

Core tool:containFilter

There is a very direct and efficient tool in the AnQiCMS template system, that iscontainFilter.Its main function is to determine whether a string, array, key-value pair (map) or struct contains the specified keyword or key name and returns a boolean value (True or False).This makes our judgment logic extremely concise.

For example, if you want to check the content of an article (article.ContentDoes it contain the word 'AnQi CMS'?

{% if article.Content|contain:"安企CMS" %}
    <p>文章内容中提到了安企CMS!</p>
{% endif %}

Similarly, if you have a tag array or list and want to know if it contains the tag 'SEO':

{% set tagList = '建站,SEO,营销'|split:',' %}
{% if tagList|contain:"SEO" %}
    <p>这个内容被标记为SEO相关。</p>
{% endif %}

containThe power of the filter lies in its versatility, whether it is for substring matching of strings or precise matching of array elements, it can handle them all, and the processing is done on the backend by the Go language, which is very efficient.

skills for dealing with complex scenarios

AlthoughcontainThe filter itself is already very powerful, but in practice, we may encounter some more detailed needs. By combining other filters, we can build a more flexible judgment logic.

1. Handle case-insensitive search

By default,containThe filter is case sensitive.If you want to perform a case-insensitive search, you can first convert the string to be checked to a uniform case (usually lowercase) and then make the judgment.lowerandupperFilter to complete this task.

{% if article.Title|lower|contain:"cms" %}
    <h1>文章标题中包含了“cms”(不区分大小写)</h1>
{% endif %}

In this way, whether the article title is "AnQiCMS", "anqicms", or "ANQICMS", the above code can accurately match.

2. Split long strings into phrase groups for more detailed search

Sometimes, you may want to check if a long string contains a certain phrase, and this phrase itself may consist of multiple words.containThe filter can directly handle this situation. However, if you need to split a long string into individual words or phrases, and then check each decomposed element separately,splitorfieldsThe filter comes into play.splitUsed to split by a specified separator, andfieldsthen split by spaces.

Suppose you have a custom fieldarticle.KeywordsStored multiple keywords, separated by commas, do you want to check if there is a specific keyword in them:

{% set keywordsArray = article.Keywords|split:',' %}
{% if keywordsArray|contain:"内容营销" %}
    <p>这篇文章与内容营销相关。</p>
{% endif %}

If your content is a long text and you want to check if a specific "word" exists, rather than a "phrase" or "sentence", and you want to control the matching boundaries more precisely, you can first split the text into an array of words:

{% set contentWords = article.Content|fields %}
{% set foundSpecificWord = false %}
{% for word in contentWords %}
    {% if word|lower == "运营" %} {# 精确匹配单个单词“运营” #}
        {% set foundSpecificWord = true %}
    {% endif %}
{% endfor %}

{% if foundSpecificWord %}
    <p>文章中明确提到了“运营”这个词。</p>
{% endif %}

Of course, for simple substring matching,article.Content|contain:"运营"it is usually more efficient and direct.

3. Efficiently check and display in loops

when processing list data (for example,archiveListortagList), we often need to make keyword judgments in each item of the loop and take different display methods based on the results.

For example, in a document list, if you want to highlight the articles that contain the word 'update' in the title:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <li {% if item.Title|contain:"更新" %}class="highlight-new"{% endif %}>
            <a href="{{item.Link}}">{{item.Title}}</a>
        </li>
    {% empty %}
        <li>暂无文章。</li>
    {% endfor %}
{% endarchiveList %}

This will automatically apply special CSS styles to articles with titles containing 'update', attracting users' attention.

Some practical scenarios and suggestions

  • SEO keyword analysis:Check the description of the current content on the article or category detail page(Description) or keywords(Keywords) to see if they contain the target SEO phrase, for internal assessment or auxiliary hints.
  • Content filtering and classification:In a custom content model, if a field stores multiple selected values (such as product features), you can usecontainTo determine whether a product has specific characteristics and filter or display it accordingly.
  • Personalized user experience:Based on whether the article content contains sensitive words or specific topics, display different prompts or related content recommendations to different user groups.
  • Performance consideration: The logical processing of AnQiCMS templates is mainly completed on the server side. The high-performance architecture of Go language ensures that even complex keyword checks can respond quickly, without affecting the loading speed of the front-end page.However, avoiding too many and too complex nested loop checks in extremely large text blocks is still a good practice.

By flexible applicationcontainFilters and auxiliary filters, you can easily implement efficient keyword checking for long strings or arrays in the AnQiCMS template, bringing your website more intelligent and dynamic content display capabilities.


Frequently Asked Questions (FAQ)

1.containCan the filter search for multiple keywords at the same time?

containThe filter can only search for one keyword at a time. If you need to check multiple keywords at the same time, you can useifthe logical operator of tagsororandCombine multiplecontainExpressions. For example:{% if article.Content|contain:"AnQiCMS" or article.Content|contain:"内容管理" %}

2. How to determine how many times a certain keyword appears in a string?

If you not only want to know if a keyword exists but also need to know how many times it appears, you can usecounta filter. For example:

Related articles

How to repeat a specific string (such as a separator) multiple times in the AnQiCMS template?

In web template design, we often encounter the need to repeatedly output a specific string or character pattern to achieve visual separation, emphasis, or layout effects.For example, you may want to display a line composed of multiple dashes between content blocks, or repeat asterisks to decorate an area.In the AnQiCMS template system, thanks to its syntax similar to the Django template engine, achieving such repeated output is very flexible and efficient.

2025-11-07

How to generate a specified number of random text placeholders when there is no actual content in the AnQiCMS template?

During the development of website templates, we often encounter such situations: the interface layout has been completed, but the actual content data is not ready.At this time, in order to ensure that the layout and visual effects of the front-end page can be accurately presented, we need some placeholder text to fill the page, simulating the existence of real content.AnQi CMS fully considers this requirement and provides a very practical template tag - `lorem`, which can help us easily generate a specified number of random texts.

2025-11-07

What are the practical scenarios for the AnQiCMS `phone2numeric` filter? How to convert letters on a phone keyboard to numbers?

In the operation of daily websites, we often encounter situations where we need to process various types of data and display them in a user-friendly manner.A phone number is a typical example. Sometimes, for marketing or brand promotion, we may see some "vanity numbers" composed of letters and numbers, such as "1-800-FLOWERS".These numbers are easy to remember, but users still need to manually convert them to pure digits when dialing.AnQi CMS as a powerful enterprise-level content management system

2025-11-07

How to print the complete type and value of a variable during the development and debugging of AnQiCMS templates for problem troubleshooting?

During the development and debugging of AnQiCMS templates, we often encounter such situations: the page displays incorrectly, or some data is not displayed as expected.At this time, we hope to 'penetrate' the variables in the template and understand what types they are and what specific values they contain.In fact, only by mastering the true state of variables can one accurately locate the problem.AnQiCMS's template system adopts syntax similar to Django template engine, which makes variable output and logical control intuitive.In templates, we usually use double curly braces `{{ variable name

2025-11-07

How does the AnQiCMS `count` filter calculate the total number of times a specific keyword appears in the article content?

## Deep Analysis: AnQiCMS `count` filter counts the number of keyword occurrences in article content In daily website operations, we often need to understand certain key information in the article content, such as how many times a specific keyword appears in the article.This is crucial for SEO optimization, content quality assessment, or internal audit.AnQiCMS as an efficient content management system provides rich template tags and filters, making this work simple and intuitive. Today

2025-11-07

How to get the first or last image address of an array (such as an image list) in AnQiCMS template?

In Anqi CMS template design, flexibly displaying and managing images is an indispensable part of building a high-quality website.When the content contains multiple images, such as group images on product detail pages or article illustrations, we often need to accurately extract one of the images, such as using the first image as a thumbnail or cover, or obtaining the last image for special display.This article will discuss in detail how to easily obtain the address of the first or last image in the image array of the AnQiCMS template.

2025-11-07

What advanced formatting options does the AnQiCMS `stringformat` filter support (such as outputting percentages, scientific notation)?

In AnQiCMS template development, the flexibility of data display is often the key to determining user experience and the professionalism of content presentation.Among them, the `stringformat` filter is undoubtedly a powerful tool that allows us to finely format various data types to meet advanced needs from simple numerical precision control to complex percentages, scientific notation, and other advanced requirements.

2025-11-07

How to safely convert a user input numeric string to an integer or floating-point number for calculation in AnQiCMS template?

In daily website operations, we often encounter the need to display or calculate user input data on the webpage.Even when fields are explicitly set as numeric types in the background, when the data is fetched to the front-end template for rendering, they are often in the form of strings.This is not a problem when displaying simple content, but once it involves numerical calculations, such as calculating the total price, calculating percentages, etc., direct string operations can lead to unexpected results and even errors.

2025-11-07