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.