How to implement a search function on the front end of a website and display a list of search results with highlighted keywords?

Calendar 👁️ 93

When building a content-rich website, providing an efficient and convenient search function is a key factor in improving user experience.AnQiCMS (AnQiCMS) took this into consideration from the very beginning of its design, allowing us to relatively easily implement search functionality on the website front end with its flexible template engine and built-in tags, and further optimize it to highlight keywords in search results prominently.

Core Mechanism: Understand the Search Principle of AnQiCMS

The core of the AnQiCMS website front-end search lies insearch/index.htmlThis template file. When a user submits a keyword through the search form on the website, that keyword will be passed as a namedqURL query parameter to the preset/searchpath. For example, if the user searches for "AnQi CMS", the URL might behttp://yourdomain.com/search?q=安企CMS.

Insearch/index.htmlin the template, the system has built-inarchiveListThe tag is very smart. It automatically identifies and utilizes the existing URLs in theqThe parameter is used to filter the relevant document content. This means that most of the search logic is handled internally by AnQiCMS, and we only need to focus on the front-end presentation.

Build a search form

The first step in implementing a search function is to provide an intuitive search form.This form is usually placed at the top of the website, in the sidebar, or on a dedicated search page.A basic search form will useGETThe method sends the user's input keyword to/searchthe path.

Here is a simple search form example.

<form method="get" action="/search">
    <div class="search-input-group">
        <input type="text" name="q" placeholder="请输入搜索关键词..." value="{{urlParams.q}}" class="search-field">
        <button type="submit" class="search-button">搜索</button>
    </div>
</form>

In this form:

  • method="get"Ensure that the keyword is passed as a URL query parameter.
  • action="/search"The path to the search results page is specified.
  • name="q"The input box is crucial, AnQiCMS'archiveListThe tag will recognize thisqParameter.
  • value="{{urlParams.q}}"This is a small trick that allows users to see the keywords they entered previously on the search results page, enhancing the user experience.urlParams.qIt will automatically retrieve the current URL inqThe value of the parameter.

Display the search results list

After the user submits a search request, AnQiCMS will loadsearch/index.htmlthe template. In this template, we usearchiveListtags to retrieve and display the list of documents found in the search.

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <div class="search-result-item">
        <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
        <p class="description">{{item.Description}}</p>
        <div class="meta">
            <span>分类:{% categoryDetail with name="Title" id=item.CategoryId %}</span>
            <span>发布日期:{{stampToDate(item.CreatedTime, "2006-01-02")}}</span>
            <span>浏览量:{{item.Views}}</span>
        </div>
    </div>
    {% empty %}
    <div class="no-results">
        很抱歉,没有找到与“{{urlParams.q}}”相关的结果。
    </div>
    {% endfor %}

    <div class="pagination-area">
        {% pagination pages with show="5" %}
            {# 分页导航的代码,可参考官方文档 #}
            {% if pages.FirstPage %}
                <a class="{% if pages.FirstPage.IsCurrent %}active{% endif %}" href="{{pages.FirstPage.Link}}">首页</a>
            {% endif %}
            {% if pages.PrevPage %}
                <a href="{{pages.PrevPage.Link}}">上一页</a>
            {% endif %}
            {% for page in pages.Pages %}
                <a class="{% if page.IsCurrent %}active{% endif %}" href="{{page.Link}}">{{page.Name}}</a>
            {% endfor %}
            {% if pages.NextPage %}
                <a href="{{pages.NextPage.Link}}">下一页</a>
            {% endif %}
            {% if pages.LastPage %}
                <a class="{% if pages.LastPage.IsCurrent %}active{% endif %}" href="{{pages.LastPage.Link}}">末页</a>
            {% endif %}
        {% endpagination %}
    </div>
{% endarchiveList %}

In the above code:

  • archiveList archives with type="page" limit="10"will automatically obtain withqThe document matches the parameters and is paginated 10 items per page.
  • for item in archivesLoop through each search result.
  • item.Title/item.Link/item.Descriptionare commonly used document fields, used to display search result summaries.
  • {% empty %}Blocks are used to display friendly prompts when there are no search results.
  • {% pagination pages with show="5" %}Tags are used to create pagination links, ensuring easy navigation among a large number of search results.

Implementation of keyword highlighting

To make the keywords in the search results more prominent, we can use the filter provided by the AnQiCMS template engine to process the title and description. The core idea is to get the user's input keywords and then replace all the matched keywords in the title and description with<mark>tags.

AnQiCMS providedreplaceFilters andsafeA filter, can help us easily achieve this.

  1. Get the search keywordInsearch/index.htmlIn the template, you can use{{urlParams.q}}Directly get the current URLqThe parameter value, i.e., the search keyword.
  2. UsereplaceFilterReplace the matched keywords in the title or description with tags containing<mark>keywords.
  3. UsesafeFilter: Due toreplaceThe filter will insert HTML tags (such as<mark>),To make the browser correctly parse these tags instead of displaying them as plain text, we need to usesafefilter.

Modify the code that displays the search results slightly to add keyword highlighting:

"twig {% set searchQuery = urlParams.q %} {# Get search keywords #}"

{% archiveList archives with type=“page” limit=“10” %}

{% for item in archives %}
<div class="search-result-item">
    <h3>
        <a href="{{item.Link}}">
            {# 对标题进行高亮处理 #}
            {% if searchQuery %}
                {{ item.Title|replace:searchQuery,'<mark>'~searchQuery~'</mark>'|safe }}
            {% else %}
                {{ item.Title }}
            {% endif %}
        </a>
    </h3>
    <p class="description">
        {# 对描述进行高亮处理 #}
        {% if searchQuery %}
            {{ item.Description|replace:searchQuery,'<mark>'~searchQuery~'</mark>'|safe }}
        {% else %}
            {{ item.Description }}
        {% endif %}
    </p>
    <div class="meta">
        <span>分类:{% categoryDetail with name="Title" id=item.CategoryId %}</span>
        <span>发布日期:{{stampToDate(item.CreatedTime, "2006-01-02")}}</span>
        <span>浏览量:{{item.Views}}</span>
    </div>
</div>
{% empty %}
<div class="no-results">
    很抱歉,没有找到与“{{urlParams.q}}”相关的结果。
</div>
{% endfor %}

<div class="pagination-area">
    {# 分页导航的代码同上 #}
    {% pagination pages with show="5" %}
        {% if pages.FirstPage %}<a class="{% if pages.FirstPage.IsCurrent %}active{% endif %}" href="{{pages.FirstPage.Link}}">首页</a>{% endif %}
        {% if pages.PrevPage %}<a href

Related articles

How to implement content pagination display and customize page navigation style in AnQiCMS template?

As the content of the website becomes richer, how to efficiently display a large amount of information while ensuring a user-friendly browsing experience is an indispensable link in website operation.In AnQiCMS, through the powerful template tag system, we can easily achieve content pagination display and flexibly customize the style of page navigation, making the website content both rich and tidy.--- ### Efficient Content Organization: Implementing Pagination of Content Lists In the AnQiCMS template, the core of implementing content pagination is to use the `archiveList` tag to retrieve document lists

2025-11-08

How to display the article list according to different sorting rules (such as latest, views, custom sorting)?

Managing website content in Anqi CMS, flexibly controlling the display order of article lists is crucial for improving user experience and content distribution efficiency.Whether you want to immediately display the latest released content to visitors, highlight the most popular hot articles, or manually adjust the arrangement of articles according to specific operational strategies, Anqi CMS provides a simple and powerful way to meet these needs.One of the core advantages of AnQi CMS is its intuitive and feature-rich template tag system.

2025-11-08

How to filter and display articles in a list or category list based on recommended attributes (such as "Top Story

In content management and website operation, how to effectively highlight key information, guide users to focus on specific articles, is the key to improving website effectiveness.AnQiCMS (AnQiCMS) provides a flexible recommendation attribute feature that allows you to easily filter and display articles in article lists or category lists based on attributes such as "Headline" and "Recommended", thus better realizing content operation strategies.

2025-11-08

How to dynamically display different group Banner slideshows on the website homepage?

The banner carousel on the homepage is an important window to attract visitors' attention and convey core information.By cleverly setting up, we can allow the home page banner slideshow to dynamically display according to different marketing goals or content themes, which can not only improve user experience but also effectively guide users to browse.AnQiCMS (AnQiCMS) offers flexible features to help users easily meet this requirement.Understanding the Banner mechanism of AnQi CMS In AnQi CMS, the management and display of banners have a clear logic

2025-11-08

How to implement filtering in the article list based on custom parameters (such as product features, price range)?

In website operation, we often need to classify and filter content lists more finely to help users quickly find the information they are really interested in.Traditional article classification can solve most problems, but when the content attributes become more complex, such as products with multiple characteristics, price ranges, or events with different themes and participation methods, a single classification seems to be inadequate.

2025-11-08

How to display the link and title of the previous and next article in AnQiCMS template?

It is crucial to provide visitors with a smooth navigation experience in website operation.When a user finishes reading an article, they naturally expect to find more related content, and the "Previous" and "Next" links are the key features to meet this need.They can not only improve the user's stay time on your website, but also have a positive impact on search engine optimization (SEO) by building an internal link structure.AnQiCMS provides concise and efficient built-in tags for template developers, allowing you to easily display links and titles of the previous and next articles on the article detail page.

2025-11-08

How to display a list of related documents on the document detail page, such as categorized recommendations or keyword-based recommendations?

In website content operation, providing more relevant and potentially interesting content to visitors is a key strategy to enhance user experience, extend website stay time, and promote in-depth content browsing.This not only effectively guides users to explore more information, but is also an important component of 'inter-page relevance' in Search Engine Optimization (SEO).In such a powerful content management system as AnQiCMS, it is easy and efficient to implement the display of related document lists on the document detail page.

2025-11-08

How to perform simple arithmetic operations such as addition, subtraction, multiplication, and division in AnQiCMS templates?

When creating templates in AnQiCMS, we often need to perform some simple numerical calculations, such as displaying the total price of goods, calculating the percentage of article reading volume, or handling the serial numbers in the list.AnQiCMS is a powerful template engine that supports direct arithmetic operations such as addition, subtraction, multiplication, and division in templates, making our content display more flexible and dynamic.

2025-11-08