How to implement a multi-level nested tree structure display in the category list?

Calendar 👁️ 97

When building website categories, we often need to display a clear, hierarchical structure, so that users can intuitively understand the attribution of the website content.AnQiCMS (AnQiCMS) provides powerful template tag features, fully supporting the implementation of multi-level nested tree structure display in category lists, helping you easily create a user-friendly navigation system.

The core of achieving this effect lies in the clever use of Anqi CMS'scategoryListThe template tag and its built-in hierarchical judgment feature. By looping in the template, you can dynamically render a beautiful tree structure based on the parent-child relationship of the categories.

Understand the classification system of Anqi CMS

In the AnQi CMS backend, under the Content Management section, the 'Document Category' function allows us to create and manage all website categories.Each category can be assigned a 'parent category', thereby naturally building a hierarchical relationship.This hierarchical relationship is the basis for displaying tree structures. For example, you can create a top-level category "Products", and then create subcategories "Mobile phones", "Computers" under it, and then create "Android mobile phones", "Apple mobile phones" under "Mobile phones", etc.

In order to display these classification levels in the front-end template, we will mainly rely oncategoryListTemplate tag. This tag can retrieve the category list under specified conditions and provides rich attributes for each category item, among whichParentId(Parent Category ID) andHasChildren(Does it have a subcategory) is the key to building a nested structure.

Step by step implementation of a multi-level nested tree structure.

Implement a multi-level nested tree structure, which usually requires recursive or multi-level loop methods to build. Here, we will use the method of multi-level loop nesting to gradually demonstrate how to implement it.

Step 1: Backend Category Settings

First, make sure that your Safe CMS backend has created categories with parent-child relationships.In the 'Content Management' -> 'Document Category' section, when adding or editing categories, set their hierarchical relationships through the 'Parent Category' option and select an appropriate 'Document Model'. For example:

  • Top Level Category:Electronics (ParentId: 0)
    • Secondary Category:Phone (ParentId: Electronics ID)
      • Third-level category:Android phone (ParentId: Mobile ID)
      • Third-level category:Apple phone (ParentId: Mobile ID)
    • Secondary Category:Computer (ParentId: Electronic Product ID)
      • Third-level category:Laptop (ParentId: Computer ID)
      • Third-level category:Desktop (ParentId: Computer ID)

Second step: Write template code

Next, in your front-end template file (for examplelist.htmlOr any page that needs to display category navigation, you can write the code in the following structure:

We first callcategoryListtags to get the list of top-level categories. To get the top-level categories, we willmoduleIdSpecify your content model ID (for example, the article model is usually1, and the product model is usually2),andparentIdthe parameter to"0".

When traversing these top-level categories, we check if each category item has a subcategory. This can be determined by usingitem.HasChildrenthe property. IfHasChildrenTrue, indicating that there are still subcategories under the current category, we can call it again internallycategoryListtag to retrieve and render these subcategories. To retrieve the correct subcategories, this timecategoryListofparentIdThe parameter needs to be set to the current parent category'sitem.Id. This pattern can be nested continuously according to your category depth requirements.

Furthermore,item.SpacerProperties can help you visually indent categories at different levels, making them look more like a tree. Please note,SpacerThe value usually contains HTML entities, so it needs to be used with|safea filter to ensure correct parsing.

This is an example of a three-level nested code snippet, you can adjust the nesting level according to your actual needs:

{% categoryList categories with moduleId="1" parentId="0" %} {# 获取顶级分类,moduleId根据实际内容模型ID填写 #}
{# 一级分类开始 #}
<ul>
    {% for item in categories %}
    <li>
        <a href="{{ item.Link }}">
            {{ item.Spacer|safe }}{{ item.Title }} {# 使用Spacer进行缩进,并显示分类名称 #}
        </a>
        {# 判断是否有二级分类 #}
        {% if item.HasChildren %}
            {% categoryList subCategories with parentId=item.Id %} {# 获取当前一级分类的子分类 #}
            {# 二级分类开始 #}
            <ul>
                {% for inner1 in subCategories %}
                <li>
                    <a href="{{ inner1.Link }}">
                        {{ inner1.Spacer|safe }}{{ inner1.Title }} {# 使用Spacer进行缩进 #}
                    </a>
                    {# 判断是否有三级分类 #}
                    {% if inner1.HasChildren %}
                        {% categoryList subCategories2 with parentId=inner1.Id %} {# 获取当前二级分类的子分类 #}
                        {# 三级分类开始 #}
                        <ul>
                            {% for inner2 in subCategories2 %}
                            <li>
                                <a href="{{ inner2.Link }}">
                                    {{ inner2.Spacer|safe }}{{ inner2.Title }} {# 使用Spacer进行缩进 #}
                                </a>
                            </li>
                            {% endfor %}
                        </ul>
                        {# 三级分类结束 #}
                        {% endcategoryList %}
                    {% endif %}
                </li>
                {% endfor %}
            </ul>
            {# 二级分类结束 #}
            {% endcategoryList %}
        {% endif %}
    </li>
    {% endfor %}
</ul>
{# 一级分类结束 #}
{% endcategoryList %}

In this code block,item.LinkIt will output the access link of the category,item.Titlewhich is the name of the category. Through multi-layer<ul>and<li>Tags, combined withitem.SpacerIndentation, a clear hierarchical classification structure is presented.

Optimization and expansion suggestions

  • CSS styling beautification: The code above only provides a basic HTML structure. You can use CSS to style different levels of<ul>and<li>Add different margins, background colors, font sizes, etc., to make the tree structure more visually appealing and readable. For example, you can use CSS selectorsul ulAdjust styles for nested lists.
  • Interactive collapsing menu:If the category hierarchy is deep, expanding all at once may cause the page to be lengthy.You can combine JavaScript (such as jQuery or other frameworks) to add a collapse/expand function to the category list.When the user clicks on the parent category, its child categories can be dynamically displayed or hidden, enhancing the user experience.
  • Performance consideration: For websites with a huge number of categories and deep levels, too many nested loops may have a slight impact on page loading speed.In most cases, the performance of Anqicms is sufficient to cope with.If an extreme situation occurs, it can be considered whether it is necessary to appropriately limit the number or depth of classification display.

By using the above method, you can achieve multi-level nested tree-like structure display in the category list of AnQi CMS, providing clearer and more convenient navigation experience for your website visitors.


Frequently Asked Questions (FAQ)

1. Why is my category not showing the hierarchical relationship, but is all spread out?This is usually because you did not correctly specify the 'parent category' when setting up categories in the background, resulting in all categories being identified as top-level categories.Please check whether the "Parent Category" field in each category under "Content Management"->"Document Categories" is configured as expected.In addition, ensure that the template containscategoryListlabel'sparentIdThe parameter settings are correct, for example, to get the top-level category should be set toparentId="0"It should be set to the parent category when getting subcategories.item.Id.

2.item.Spacer|safeof|safeWhat is its purpose, can it be removed? |safeIt is a filter, its role is to tell the template engine,item.SpacerThe content within the variable is safe HTML and does not require escaping.item.SpacerIt usually contains HTML entities for indentation (such as), if removed|safeThese HTML entities may be displayed directly as text, rather than being parsed by the browser as indentation, thereby destroying the visual hierarchy. Therefore, it is not recommended to remove them.|safe.

How to limit the display depth of the category tree, for example, to display only two levels of categories?To limit the display depth, you can control the number of loop levels in the template code. For example, if you only want to display up to the second level in the above code, you just need to delete or comment out the third levelcategoryList subCategories2You can control the display depth of the category tree by modifying the conditional judgment and loop structure within it.

Related articles

How to retrieve and display detailed information of a specified category, including its description, Banner image, and Logo?

In a content management system, categories are not only the form of content organization, but also the core of website structure and user navigation.Flexibly obtain and display detailed information of a specific category, such as its description, unique banner image and logo, which is crucial for creating attractive and informative pages.AnQiCMS (AnQiCMS) provides an intuitive and powerful template tag to meet this need, allowing you to easily achieve this requirement.### Core Function Tag

2025-11-08

How to retrieve and loop through all document lists under a specific Tag (label) in the template?

In AnQi CMS, content organization can not only be achieved through traditional classification methods, but also flexible "Tag" mechanisms provide a wide space for content association and user search.When you want to display all documents under a specific tag in a certain area of the website, such as the sidebar, related recommendation modules, or even a dedicated Tag aggregation page, AnQi CMS provides a powerful and intuitive template tag that makes this process easy.This article will delve into how to use the Anqi CMS template

2025-11-08

How does AnQiCMS define and display related articles? Is it based on keywords or manual association?

In website operation, recommending relevant articles is an important strategy to enhance user experience, extend user stay time, and optimize on-site SEO.AnQiCMS provides a flexible and efficient mechanism to define and display related articles, allowing operators to choose between intelligent recommendations or manual association according to their actual needs. ### Smart Recommendation: Dynamic Association Based on Keywords and Tags The smart recommendation mechanism of AnQiCMS mainly relies on the keywords and tags set in the article content. When you edit articles in the background, you can set: * **Document keywords

2025-11-08

How to dynamically fetch and display the previous and next articles of the current article on the article detail page?

In website operation, how to allow users to smoothly jump to related or the next article after reading an article is the key to improving user experience and website stickiness.Especially for sites with a large amount of content, such as blogs, information stations, or product display websites, a intuitive 'Previous/Next' navigation function is particularly important.It can not only guide users to deeply browse and reduce the bounce rate, but also provide more internal links for search engines to optimize the SEO performance of the website.AnQiCMS (AnQiCMS) is a powerful content management system that fully considers this need

2025-11-08

How to display the main category in the navigation bar and show the latest products under this category in the dropdown menu?

In website operation, a clear and effective navigation system is the key to improving user experience and website professionalism.AnQiCMS (AnQiCMS) with its flexible content management and powerful template engine, can help us easily achieve complex navigation requirements.Today, let's discuss how to display the main categories in the website's navigation bar and also show the latest products under the category in a dropdown menu when the mouse hovers over it.### One, Understand the navigation and content management basics of AnQiCMS One of the core advantages of AnQiCMS lies in its modular content management system

2025-11-08

How to get and loop through all independent pages in AnQiCMS template (such as About Us)?

In AnQi CMS, sometimes we need to list some independent pages in the website's navigation bar, footer, or other specific areas, such as "About Us", "Contact Us", "Privacy Policy", and so on.These pages usually contain fixed content and do not belong to a specific category or article model. AnQiCMS refers to them as 'single pages'.Fortunately, AnQiCMS provides a very intuitive and powerful template tag that can easily retrieve and loop through information for these single pages.### Core Tag

2025-11-08

How to get the complete content, SEO information, and associated images of a single page?

In daily website operations, independent pages such as "About Us", "Contact Information", etc., play an important role in conveying core information and shaping the brand image.As content operators, we often need to gain a deep understanding of the structure of these pages, including their main content, SEO information, and all associated image resources, in order to carry out fine management, optimization iteration, or flexible page layout.AnQiCMS provides an intuitive and powerful template tag system, making it easy to obtain these page data.

2025-11-08

How to retrieve and loop the list of friend links in the AnQiCMS template?

In website operation, friendship links are an important means to enhance website authority, increase external traffic, and promote cooperative relations.A convenient management and flexible display of友情链接 function is crucial for any content management system.AnQiCMS as an efficient content management system provides an intuitive way to manage and obtain the list of friend links in templates.This article will thoroughly introduce how to obtain and loop through the list of friendship links on AnQiCMS templates, helping you easily realize the interconnection of websites.

2025-11-08