How to display dynamic data in the AnQiCMS navigation menu, such as the number of unread messages?

Calendar 👁️ 73

As an experienced website operations expert, I am well aware of the core position of the navigation menu in user experience and website architecture.It is not only the index of the content, but also the key to users quickly obtaining the information they need and improving conversion efficiency.Today, we will delve into how to cleverly integrate dynamic data into the navigation menu of AnQiCMS (AnQi CMS), such as the number of unread messages that are of great concern, which will undoubtedly greatly enhance user interaction and the vitality of the site.

Insight requirements: The challenge of integrating static navigation with dynamic data

The traditional website navigation menu is often static and rarely changes once set.However, in today's era where users increasingly pursue personalization and real-time feedback, if the navigation menu can come alive, for example, after the user logs in, the 'Messages' entry can display unread counts like '(3)' in real time, it will undoubtedly greatly enhance the user experience and guide users to check important information in a timely manner.In AnQiCMS, a content management system known for its efficiency and customizability, achieving this goal is not out of reach. It benefits from its flexible template mechanism and the high-performance backend of Go language.

One of AnQiCMS's core advantages is that it adopts a syntax similar to Django's template engine, allowing operators and developers to deeply customize the front-end display. We through{{变量}}to output data, through{% 标签 %}To implement logic control and data calls. This provides a solid foundation for displaying dynamic data.However, data such as the number of unread messages usually requires combining the user's login status and backend business logic to be calculated in real-time, which goes beyond the scope of direct invocation of traditional template tags.

The core idea of AnQiCMS for dynamic data display

To display dynamic data in the AnQiCMS navigation menu, especially data like the number of unread messages that requires user context and real-time calculation, we usually need to combineBackend data interface expansionwithPartial dynamic loading of front-end templateTwo strategies. The modular design of AnQiCMS and the powerful features of Go language provide convenience for this customization.

Step 1: Build the backend dynamic data interface (API)

For example, the template tags of the current AnQiCMScommentListorguestbookIt is mainly used to display comment or message list and does not directly provide a refined statistical function such as the number of unread messages. Therefore, the most effective way to obtain the total number of unread messages for a specific user or under specific conditions isExtend the AnQiCMS backend service, create a dedicated data interface.

AnQiCMS is developed based on the Go language, its modular architecture allows developers to add custom business logic without affecting the core system. We need to build a lightweight API endpoint (such as/api/user/unread_messagesIt is responsible for:

  1. Identify the current user: Determine which logged-in user the current request is from, through session or token, etc.
  2. Query the databaseAccess the data table storing messages, comments, or messages (for example, if we consider comments as messages, a query might becommentstable; if messages require user handling, a query might beguestbooktable).
  3. Filter "Unread" status: According to the message status field defined in the business logic (for examplestatus=0represents unread,is_read=false), filter out the records that meet the conditions.
  4. Count the numberCount the filtered records.
  5. Return dataReturn the statistical results in JSON format, for example,{"count": 3}.

This backend extension process requires a certain level of Go language development skills, but the AnQiCMS documentation emphasizes its high adaptability to secondary development and personalized adjustments, therefore, it is a feasible path for those with a development team or who are familiar with Go language.

Step two: Modify the navigation menu template and reserve a dynamic data display position

We need to reserve space for dynamic data in the front-end template. The template files of AnQiCMS are usually located in/templatethe directory, and the common part of the navigation menu is likely to be located inpartial/header.htmlorbash.htmlThis file is mentioned inincludeTag references. We can usetag-/anqiapi-other/165.htmlThe tags mentioned in thenavListTo render navigation structure.

Assuming our navigation menu has an entry named "Message", its HTML structure may be similar to:

{% navList navs %}
    {%- for item in navs %}
        {%- if item.Title == "消息" %} {# 假设我们找到“消息”这个导航项 #}
            <li class="{% if item.IsCurrent %}active{% endif %}">
                <a href="{{ item.Link }}">{{item.Title}} <span id="unread-message-count" class="badge"></span></a>
            </li>
        {%- else %}
            <li class="{% if item.IsCurrent %}active{% endif %}">
                <a href="{{ item.Link }}">{{item.Title}}</a>
            </li>
        {%- endif %}
    {% endfor %}
{% endnavList %}

In the above code, we added a label with a unique ID after the link text of the “Message” navigation item.<span id="unread-message-count" class="badge"></span>. ThisspanThe tag has a unique ID (unread-message-countIt will be the target element for our front-end JavaScript to update data.In its initial state, it can be empty or display a default value (such as 0), and will be updated after the dynamic data is loaded.

Step 3: Get and render dynamic data on the front-end JavaScript

The final step is to write frontend JavaScript code, which sends a request to our backend API after the page is loaded to get the number of unread messages and display them in the navigation menu. To optimize the user experience, this JavaScript code can be placed at the bottom of the page. ...</body>Before the tag) or execute after the page is fully loaded.

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 假设用户已登录,并且您有办法获取到用户ID或其他认证信息
    // 实际项目中,您可能需要将这个API请求绑定到用户登录状态
    // 或者后端直接在页面渲染时提供一个临时的token供前端使用

    fetch('/api/user/unread_messages') // 替换为您的实际API地址
        .then(response => {
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            return response.json();
        })
        .then(data => {
            const unreadCountElement = document.getElementById('unread-message-count');
            if (unreadCountElement) {
                if (data.count > 0) {
                    unreadCountElement.textContent = `(${data.count})`; // 显示如 (3)
                    unreadCountElement.style.display = 'inline-block'; // 确保可见
                } else {
                    unreadCountElement.style.display = 'none'; // 没有未读消息则隐藏
                }
            }
        })
        .catch(error => {
            console.error('获取未读消息数量失败:', error);
            // 可以在此处添加错误提示或保持默认值
        });
});
</script>

This JavaScript code takes advantage of the features provided by modern browsers.fetchAn API that asynchronously requests the backend interface after the page is loaded. Once the data is obtained, it will find the ID ofunread-message-countThe element is updated and its content is updated. In this way, users do not need to refresh the entire page and can see the real-time updated number of unread messages, greatly improving the fluidity of interaction.

Advanced consideration and optimization

In the actual deployment, in addition to the above steps, we also need to consider some

Related articles

Does AnQiCMS have a built-in caching mechanism when fetching data from the navigation list tags?

Dear operations partners, hello!As an expert with many years of experience in website operations, I am well aware of the importance of website performance for user experience and Search Engine Optimization (SEO).AnQiCMS, with its excellent performance and flexibility, has gained a place in the field of content management.Today, we will delve deeply into a common concern: Does AnQiCMS's navigation list tag have a built-in caching mechanism when fetching data?This is not only about the technical implementation, but also closely related to the efficiency of our daily content operation.

2025-11-07

How to configure the mouse hover effect or animation of navigation menu items in AnQiCMS backend?

## Mastering AnQiCMS Navigation Menu Hover Effect: The Perfect Combination of Backend Configuration and Frontend Ingenuity In today's web design, the navigation menu is no longer just a tool to guide users through the site; it is also an important window to enhance user experience and showcase brand vitality.A well-designed, smooth interactive navigation menu, especially one with mouse hover effects or animations, can make a website come alive instantly.As an experienced website operations expert, I know that many AnQiCMS users hope to add such interactivity to their website menus.But it should be clear that

2025-11-07

Does AnQiCMS navigation menu support custom icon fonts, such as Font Awesome icons?

In the daily operation of AnQiCMS, the design of the navigation menu and the user experience are often one of the key factors for the success of the website.Many operators hope to be able to add intuitive icons to the navigation menu, such as popular Font Awesome icons, to enhance aesthetics and information transmission efficiency.Then, does AnQiCMS support this custom icon font feature?As an experienced website operations expert, I will give you a detailed explanation.### Deep Analysis of AnQiCMS Navigation Function First, let's examine

2025-11-07

Can AnQiCMS navigation tags call other navigation categories in non-navigation templates (such as article detail pages)?

As an expert in website operation for many years, I fully understand that how to flexibly call and display information in a content management system is the key to improving website user experience and operational efficiency.AnQiCMS (AnQiCMS) provides many conveniences in this aspect with its excellent flexibility and powerful functions.TodayThe answer is affirmative, not only can it

2025-11-07

Does the AnQiCMS navigation menu display different navigation structures according to device type (PC/Mobile)?

Good, as an experienced website operation expert, I am very willing to deeply analyze the ability of AnQiCMS in the differentiation display of navigation menus and transform it into an article that is easy to understand and practical. --- ## Safe CMS Navigation Menu: The Secret of PC/Mobile End Differentiation Display In today's multi-screen interconnection era, users visit websites with various types of devices.Whether it is the wide screen on the PC end or the compact interface on the mobile end, users expect to get a smooth and intuitive browsing experience.

2025-11-07

How to integrate search boxes, shopping carts, and other functional elements into the AnQiCMS navigation menu?

##驾驭AnQiCMS navigation: Skillfully integrate search, shopping cart and other functional elements to create an efficient user experience As an experienced website operation expert, I know the importance of an efficient and user-friendly navigation menu for the success of the website.In today's era of information overload, users expect to quickly find the content they need, and elements such as search boxes and shopping carts, if cleverly integrated into navigation, can undoubtedly greatly enhance user experience and website conversion rates.AnQiCMS, this is an enterprise-level content management system built based on the Go language, with its high efficiency, customizable, and easy to expand features

2025-11-07

How to use the `forloop.Counter` variable in the AnQiCMS navigation list tag in multi-level navigation?

As an experienced website operations expert, I am well aware of the importance of an efficient and flexible CMS system for content management and user experience.AnQiCMS (AnQiCMS) provides strong support for content creators and operators with its high-performance architecture based on the Go language and a Django-style template engine.In AnQiCMS template development, flexibly using various tags is the key to enhancing website interactivity and maintainability.

2025-11-07

How does AnQiCMS template truncate and display the description content of a navigation item if it is very long?

As an experienced website operations expert, I am well aware that in today's user experience-oriented era, even the details such as website navigation contain huge optimization space.AnQiCMS as an efficient and flexible content management system, its powerful template function provides us with enough 'magic' to meet various front-end display challenges.Today, let's talk about a common yet often overlooked issue: how should we elegantly truncate the display of navigation item descriptions in the AnQiCMS template.### Optimize Navigation Experience

2025-11-07