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 just an index of content, but also the key to users quickly obtaining the information they need and improving conversion efficiency.Today, we will delve into how to ingeniously integrate dynamic data into the navigation menu of AnQiCMS (AnQi CMS), such as the highly关注的“number of unread messages”, which undoubtedly can greatly enhance user interaction and the vitality of the site.

Insight Requirement: The Challenge of Integrating Static Navigation with Dynamic Data

The traditional website navigation menu is often static, rarely changing once set.However, in today's world where users are increasingly seeking personalization and real-time feedback, if the navigation menu can be made 'alive', for example, by displaying a real-time unread count like '(3)' next to the 'Messages' entry after the user logs in, it would undoubtedly greatly enhance the user experience and guide users to promptly review important information.In AnQiCMS, a content management system renowned 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 strengths is its adoption of syntax similar to Django's template engine, allowing operators and developers to deeply customize the frontend display. We have{{变量}}Output data, through{% 标签 %}To implement logical control and data invocation.This provides a solid foundation for us to display dynamic data.However, data such as 'number of unread messages' usually needs to be calculated in real-time by combining the user's login status and the backend business logic, which goes beyond the direct call scope 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, which requires user context and real-time calculation, we usually need to combineThe expansion of the back-end data interfaceWithPartial dynamic loading of the 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)

Current AnQiCMS template tags, for examplecommentListorguestbook主要用于displaying comment or message lists and does not directly provide a fine-grained statistic function like '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 backend service of AnQiCMS, create exclusive data interfaces.

AnQiCMS is developed in 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 and other methods.
  2. Query the databaseAccess the data table for storing messages, comments, or notes (for example, if we consider comments as messages, we may querycommentstable; if notes require user handling, we may queryguestbooktable).
  3. Filter the "Unread" status: Based on the message status field defined in the business logic (such asstatus=0representing unread,is_read=false), filter out the records that meet the conditions.
  4. Count the numberCount the records filtered.
  5. Return data: Return the statistics result in JSON format to the front-end, for example{"count": 3}.

This backend extension process requires certain Go language development skills, but the AnQiCMS documentation emphasizes its high adaptability to secondary development and customization, so it is a feasible path for those with a development team or operators familiar with Go language.

Second step: Modify the navigation menu template and reserve a position for dynamic data display

Next, we need to reserve a position for dynamic data in the frontend template. The template files of AnQiCMS are usually located in/templatedirectory, and the public part of the navigation menu is likely to be inpartial/header.htmlorbash.htmlFiles of this typeincludewe can use tag referencestag-/anqiapi-other/165.htmlmentioned in the documentnavListto render the navigation structure.

Assume that our navigation menu has an entry named "Messages", and 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 after the link text of the "Messages" navigation item.<span id="unread-message-count" class="badge"></span>. ThisspanTag with a unique ID (unread-message-countIt will be the target element for us to update data with our front-end JavaScript.It can be empty or display a default value (e.g., 0) initially, and will be updated after the dynamic data is loaded.

Step 3: Front-end JavaScript fetches and renders dynamic data

The final step is to write the front-end JavaScript code, which sends a request to our backend API after the page is loaded, retrieves the number of unread messages, and displays it in the navigation menu. To optimize the user experience, this JavaScript code can be placed at the bottom of the page (</body>Labels before, or after the page has 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.fetchAPI, it makes an asynchronous request to the backend interface after the page is loaded. Once the data is obtained, it will find the element with ID ofunread-message-countThe element, and update its content. This way, users do not need to refresh the entire page to see the real-time update of the number of unread messages, greatly enhancing the fluidity of interaction.

Advanced Considerations and Optimization

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