How to get the number of top-level menu items in the website navigation list `navList`?

Calendar 👁️ 55

In website content operation, the navigation menu is the first door for users to interact with the website content. AnQiCMS (AnQiCMS) provides flexiblenavListTags, help us easily manage and display website navigation. Sometimes, to achieve specific layouts, styles, or for dynamic adjustments, we need to know the specific number of top-level navigation menu items on the website.

This article will thoroughly introduce how to obtain the website navigation list in the AnQiCMS templatenavListof the top-level menu items.

UnderstandingnavListNavigation tags

In the AnQiCMS template design,navListTags are the core tools used to call and render the website navigation menu. They are used in the template in the following way:

{% navList navs %}
    {# 这里是导航项的循环内容 #}
{% endnavList %}

In this code block,navsis a variable that carries the collection of all top-level navigation menu items obtained from the background. EachnavsofitemA navigation object is independent, containing a title, link, and may even include its own sub-navigation list (item.NavList) and our goal is to calculate thisnavsHow many top-level menu items are there in the set.

Use cleverlylengthThe filter calculates the number.

AnQiCMS's template engine provides a rich set of "filter" functions for processing and converting variable data. Among them,lengthThe filter is specifically used to obtain the length of strings, arrays (or lists) and other iterable objects.

Its basic usage is very intuitive:

{{ 变量 | length }}

Therefore, to getnavsThe number representing the top-level navigation menu items list, we just need tolengtha filter tonavsthe variable.

Practice: Step by step to get the number of navigation items

Now, let's transformnavListTags andlengthCombine the filters to get and utilize the number of navigation items.

Step 1: CallnavListLabel and define variables

First, use it in your template file,navListLabel to get navigation data. We usually assign the result to a variable, such asnavs:

{% navList navs %}
    {# 此时,navs 变量已包含所有顶级导航项的数据 #}
    {# 这里可以继续循环输出导航,或者先获取数量 #}
{% endnavList %}

Second step: uselengthFilter to get the number and display

InnavListInside the tag,navsThe variable is available. We can apply it directlylengthA filter to get the number of top-level menu items. To better utilize this number, we can use{% set %}a label to store it in a new variable:

{% navList navs %}
    {% set topLevelCount = navs|length %} {# 获取顶级菜单项的数量并存储在 topLevelCount 变量中 #}

    <p>当前网站共有 <strong>{{ topLevelCount }}</strong> 个顶级导航菜单项。</p>

    <ul class="main-nav">
        {% for item in navs %}
            <li class="nav-item">
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {# 这里可以继续处理子导航项 item.NavList #}
            </li>
        {% endfor %}
    </ul>
{% endnavList %}

By this means,topLevelCountThe variable will accurately store the number of top-level navigation menu items on your website.

An example of more advanced usage: Dynamic style adjustment

After understanding the number of top-level menu items, you can apply them to more flexible template designs, such as dynamically adjusting CSS styles based on the number of menus.

Assume you want the navigation bar to become more compact when the top-level menu items exceed 5; if fewer than 5, use a wider layout:

{% navList navs %}
    {% set topLevelCount = navs|length %}

    <nav class="main-navigation {% if topLevelCount > 5 %}compact-menu{% else %}wide-menu{% endif %}">
        <ul>
            {% for item in navs %}
                <li class="nav-item">
                    <a href="{{ item.Link }}">{{ item.Title }}</a>
                    {# 处理子菜单 #}
                    {%- if item.NavList %}
                        <ul class="sub-nav">
                            {%- for inner in item.NavList %}
                                <li class="sub-nav-item"><a href="{{ inner.Link }}">{{ inner.Title }}</a></li>
                            {% endfor %}
                        </ul>
                    {% endif %}
                </li>
            {% endfor %}
        </ul>
    </nav>
{% endnavList %}

In this example, we base it on.topLevelCountvalue, dynamically add or remove<nav>to the elementcompact-menuorwide-menuBy class, it can achieve adaptive layout under different numbers of menu items.

Summary and Application Scenarios

BynavListLabel combinationlengthFilter, you can easily get the number of top-level navigation menu items on the AnQiCMS website.This method is not only simple and efficient, but also provides great convenience for the customization of the website.

After mastering this skill, you can apply it to various scenarios, such as:

  • Dynamic layout adjustment:Automatically switch navigation layout based on the number of menus (such as horizontal, vertical, or different spacing).
  • JavaScript interaction:In the frontend script, retrieve the number of menus to initialize specific sliders, collapsing menus, or other interactive components.
  • Content auditing and management:Quickly check the navigation structure to ensure that the number of top-level menus conforms to the website plan.
  • SEO Optimization:Ensure the rationality of navigation levels and quantities, which helps search engines better understand the website structure.

Frequently Asked Questions (FAQ)

  1. navListin the labelnavsCan the variable name be changed arbitrarily?Yes,navsIt is just an example variable name. You can change it to any name you like, such asmainNavItemsortopMenus. The key is to ensure{% navList 新变量名 %}/{{ 新变量名|length }}and{% for item in 新变量名 %}the variable names within it remain consistent.

  2. Can I get the number of secondary menus or deeper level menus?Of course you can.navListEach top-level navigation item returned by the tagitemIf there is a submenu in the object, there will be oneNavListfields such asitem.NavList)。You can go through{{ item.NavList|length }}To get the number of secondary menus under a specific top-level menu item. For example:

    {% navList navs %}
        {% for item in navs %}
            <p>顶级菜单 "{{ item.Title }}" 包含 {{ item.NavList|length }} 个子菜单。</p>
        {% endfor %}
    {% endnavList %}
    
  3. If my website has not set any navigation menus,lengthwhat will the filter return?If your website has not set any navigation menus in the AnQiCMS backend or currentlytypeIdthere are no menu items in the specified navigation category, thennavsThe variable will be an empty list. In this case,navs|lengthit will be returned safely0. You can use{% if navs|length > 0 %}such conditional judgments to determine whether to render the navigation area.

Related articles

How to check how many images are included in the group image `archive.Images` array on the article detail page?

It is crucial to manage the image display on the article detail page flexibly and accurately when building website content in AnQi CMS.Especially when we need to use multiple images to enrich the content of an article, the collage feature (usually corresponding to the `archive.Images` field) provides an efficient and convenient solution.In the operation, sometimes we need to understand how many images a specific article detail page contains, whether it is for page layout design, content statistics, or executing logic judgments under specific conditions.This article will elaborate on how to accurately check in AnQi CMS templates

2025-11-08

How to limit the maximum number of characters that `archive.Content` displays in the summary in the template?

In website operation, how to efficiently display content summaries that can attract visitors to click and maintain the page tidy is a common and important issue.For those who use AnQiCMS, we often need to extract the essence of the document content as a summary to be displayed on list pages, search result pages, or related article recommendation modules.This article will introduce how to precisely control the maximum number of characters displayed in the `archive.Content` field in the AnQiCMS template summary.### Understand `archive.Content`

2025-11-08

How to judge the length of the article summary `archive.Description` to decide whether to display the 'Read More' link?

In website operation, the neatness of the content list page and the user experience are crucial.When the article summary is too long, it may not only occupy too much page space, affecting the overall layout beauty, but may also dilute the guiding role of the 'Read More' link.Therefore, deciding intelligently whether to display a "Read More" link based on the actual length of the article summary is an effective strategy to enhance the professionalism and user-friendliness of the website.AnQiCMS (AnQiCMS) provides powerful and flexible template functions, making it simple and efficient to meet this requirement.### Understand `archive

2025-11-08

How to get the character length of the article title `archive.Title` for content truncation display?

In website content display, controlling the length of article titles is a common requirement, especially in list pages, recommended positions, and other scenarios, where overly long titles may destroy the page layout and affect user experience.AnQiCMS provides powerful and flexible template tags and filters to help users easily obtain and truncate the display of article titles `archive.Title`. ### Article Title in AnQiCMS Template In the AnQiCMS template, when we handle article data, we usually go through

2025-11-08

How to judge if the length of the user comment content `comment.Content` exceeds the limit for front-end verification?

In website operation, the comment feature is an important part of user interaction.To maintain a good community environment and data quality, we usually limit the length of the comments submitted by users.Front-end validation plays a crucial role in this process, providing immediate feedback before submission to avoid failure due to content length, thereby enhancing user experience and reducing server load.How can we judge whether the length of the user comment content `comment.Content` exceeds the limit in the website built using AnQiCMS?

2025-11-08

How to get the total length of the document list `archives` being traversed in the `for` loop?

In AnQiCMS template development, we often need to traverse document lists, such as through the `archiveList` tag content.In such a `for` loop, understanding the total length of the current list is a very practical need, as it can help us implement some specific display logic, such as showing 'Article N of M' or determining if the list is empty.The AnQi CMS template engine adopts Django's syntax, providing a set of intuitive and powerful tags and filters to process data.To get `for`

2025-11-08

How to dynamically display the character length of the website name `SiteName`, such as for SEO title preview?

In content operation and website SEO optimization, the title plays a crucial role.A well-constructed SEO title can not only attract the attention of users, but also effectively improve the visibility of the page in the search engine results page (SERP).Among them, the character length of the title is a detail that should not be ignored.Title length can cause it to be truncated, affecting information delivery; too short may not fully utilize the display space, missing the opportunity to attract users.AnQiCMS (AnQiCMS) is a powerful content management system that provides a rich set of tools for SEO optimization

2025-11-08

How to determine if the `linkList` friendship link list returns an empty result and decide whether to display the friendship link block?

In website operation, friendship links are an important part of enhancing website authority and promoting SEO, and can also provide users with more valuable external resources.However, during the process of website construction, friendship links are not always full.If the friend link list is empty but still displays an empty link area on the page, it will undoubtedly affect the overall aesthetics and professionalism of the website.AnQiCMS provides flexible template tags, allowing us to intelligently judge whether the friend link list is empty and decide whether to display the corresponding block according to the actual situation. Next

2025-11-08