How to loop through and display all subcategories under a specified category in a template?

Calendar 👁️ 68

How to elegantly display all subcategories under a specified category in the Anqi CMS template?

For a content-rich website, a clear classification structure is the key to improving user experience and search engine optimization.AnQiCMS (AnQiCMS) with its flexible template engine and powerful tag system, allows you to easily traverse and display all subcategories under a specified category on the website front-end, whether it is a direct subcategory or a multi-level nested subcategory, you can do it with ease.

Today, let's discuss how to implement this feature in the Anqi CMS template together.

Understand the Core:categoryListTag

In Anqi CMS, the core tool to achieve this goal is powerfulcategoryListTemplate tag. This tag is specifically used to retrieve the classification data of a website, and through different parameter settings, you can accurately obtain the required classification list.

While usingcategoryListWhen labeling, there are several key parameters that you need to understand:

  • moduleId: This parameter is used to specify which content model's categories you want to retrieve. For example, if your website is mainly centered around the 'article' and 'product' content models, then the ID of the 'article model' might be1The ID of the 'Product Model' might be2. You can view the specific IDs of each model in the 'Content Management' -> 'Content Model' section of the Anqi CMS backend.
  • parentIdThis is the core parameter controlling the classification hierarchy.
    • When you set it to"0"it will retrieve all under the specified model.top-level categories.
    • When you set it to the ID of a certain category (for exampleitem.IdifitemIs a category object that has been obtained, it will obtain the categories under this categoryDirect subcategory.
  • siteId: If you have enabled multi-site management and need to retrieve data from other sites, you can specify the site ID through this parameter.In most cases, we do not need to fill in manually, the system will automatically retrieve the data of the current site.
  • allIf you want to get all categories under a specified model (without levels), you can set it toall=true.

categoryListThe tag will return an array of category objects, you can use{% for ... in ... %}Loop through the tags to traverse these categories and extract theirTitle(Category name),Link(Category link),HasChildren(Whether it includes subcategories) and other properties are displayed.

Display the direct subcategories: Step 1.

Suppose you have a "news

{# 首先,我们获取“新闻”分类(ID为10)下的所有直接子分类 #}
{% categoryList subCategories with moduleId="1" parentId="10" %}
    <ul class="sub-category-list">
        {% for category in subCategories %}
            <li>
                <a href="{{ category.Link }}">{{ category.Title }}</a>
            </li>
        {% else %}
            <li>当前分类下暂无子分类。</li>
        {% endfor %}
    </ul>
{% endcategoryList %}

In this code block,moduleId="1"Assume your news belongs to the article model.parentId="10"Then it specifies the direct subcategory of the category with ID 10.forLoop throughsubCategoriesArray, then we usecategory.Linkandcategory.TitleTo generate links and display category names. If there are no subcategories,{% else %}the content of the block will give a friendly prompt.

Loop through multi-level subcategories: implement deep nesting

Many times, our classification structure may not be just two levels, but three, four, or even more.The AnQi CMS template engine supports nested loops, allowing you to easily display multi-level subcategories.Here, we use the example of displaying three-level categories to show you, and you can expand to a deeper level as needed.

{# 获取所有顶级分类(假设 moduleId="1" 对应文章模型) #}
{% categoryList level1Categories with moduleId="1" parentId="0" %}
    <ul class="level-1-categories">
        {% for category1 in level1Categories %}
            <li>
                <a href="{{ category1.Link }}">{{ category1.Title }}</a>
                {# 判断当前一级分类是否有子分类 #}
                {% if category1.HasChildren %}
                    {# 如果有,则获取它的直接子分类,作为二级分类 #}
                    {% categoryList level2Categories with parentId=category1.Id %}
                        <ul class="level-2-categories">
                            {% for category2 in level2Categories %}
                                <li>
                                    <a href="{{ category2.Link }}">{{ category2.Title }}</a>
                                    {# 再次判断当前二级分类是否有子分类 #}
                                    {% if category2.HasChildren %}
                                        {# 如果有,则获取它的直接子分类,作为三级分类 #}
                                        {% categoryList level3Categories with parentId=category2.Id %}
                                            <ul class="level-3-categories">
                                                {% for category3 in level3Categories %}
                                                    <li>
                                                        <a href="{{ category3.Link }}">{{ category3.Title }}</a>
                                                        {# 您可以在这里继续嵌套,获取四级、五级分类... #}
                                                    </li>
                                                {% endfor %}
                                            </ul>
                                        {% endcategoryList %}
                                    {% endif %}
                                </li>
                            {% endfor %}
                        </ul>
                    {% endcategoryList %}
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endcategoryList %}

In this code, we first retrieve allparentId="0"of the top-level categories. When iterating over each top-level category (category1), we use{% if category1.HasChildren %}To determine if it has child categories. If there are child categories, we will go through nestedcategoryListtags, setparentIdto the current category ID (for examplecategory1.IdThis pattern can be flexibly extended to any classification depth required by your website to obtain and display the lower-level categories.

Some tips and **practical advice

  • Template File LocationYou should place these template codes in the Anqi CMS template directory under.htmlfile, for exampletemplate/您的模板名称/partial/category_nav.html, and then you can use it in the main template{% include "partial/category_nav.html" %}to refer to.
  • Get the category ID of the current page: If you want to get the subcategories of the category belonging to the current page, you can use{{category.Id}}(on the category detail page) or{{archive.CategoryId}}(on the document detail page) asparentIdthe value.
  • to optimize the display: BesidesTitleandLink, the category object also providesLogo(Category Large Image),Thumb(Category Thumbnail),Descriptionand other properties. You can customize according to your design needs, in<a>Add images, descriptions, and other information within or next to the tag to enrich the display effect of the classification.
  • Performance consideration: Although Anqin CMS is based on Go language and has high-performance characteristics, in extreme complex deep nesting and large data scenarios, excessive nesting loops may have a slight impact on the rendering speed of the front-end.In most cases, for the common 3-5 level classification depth of websites, this method is efficient and worry-free.

By using the above method, you can flexibly navigate through the Anqi CMS template according to your design requirements, loop through and display all subcategories of the website, and provide visitors with a clear and intuitive navigation experience.


Frequently Asked Questions (FAQ)

1. How to determine if a category has subcategories in a template?

You can use it in the loop to traverse category items{% if item.HasChildren %}to make the judgment.HasChildrenIt is a boolean property of the category object, if it istrueIt indicates that the category has subordinate subcategories.

2. I want to display all the documents under the category instead of the subcategory list, which tag should I use?

If you want to get the document list under a specified category (or its subcategories)

Related articles

How to embed a comment list on the page and control its pagination display?

In website operation, user interaction is the key to enhancing site activity and content value.AnQiCMS provides a set of intuitive and powerful features that help us easily embed comment functions in pages and flexibly control the display of comment lists, especially its pagination management, which is crucial for pages with a large number of user comments. ### Enable comment functionality to bring content to life Firstly, we need to ensure that the comment functionality is enabled on the backend so that users can post comments.Once the comment feature is activated

2025-11-09

How to enable Markdown rendering and correctly display mathematical formulas and flowcharts in AnQiCMS?

In AnQiCMS, if you want to make your content more expressive, especially when it comes to displaying complex mathematical formulas or clear flowcharts, it is a very effective solution to flexibly use the Markdown editor.The new version of AnQiCMS has provided good support for this.Next, we will explore together how to enable these features in AnQiCMS, making your website content come alive.

2025-11-09

How to display additional field data in the front-end template after customizing the content model?

AnQiCMS with its flexible content model function has brought great convenience to us in managing various types of website content.Whether it is an article, product, event, or any other content type that requires special fields, we can easily customize fields in the background to meet unique business needs.But when we eagerly create new fields in the background and fill them with data, new problems also arise: How can we accurately display these newly added custom field data on the front page of the website for visitors?Don't worry, AnQiCMS

2025-11-09

How to implement the function of displaying and switching content in multiple languages?

Make your website go global: Anqi CMS multilingual content strategy and implementation In today's globalized digital age, many businesses and content creators hope that their websites can reach a wider audience.This means providing content display and switching functions in multiple languages to meet the reading habits of users in different countries and regions.AnQiCMS (AnQiCMS) is an efficient content management system that fully considers this requirement, providing a flexible solution to help you easily implement the multilingual function of the website.In AnQi CMS, implement multi-language display and switching of content

2025-11-09

How to display a second-level dropdown menu in the navigation menu and associate different content?

AnQi CMS provides a直观and powerful navigation menu management system, allowing you to easily build a clear, user-friendly navigation structure for your website, including multi-level dropdown menus.This not only improves the user experience of the website, but also helps search engines better understand the hierarchy of your website content, thus optimizing SEO performance. ### Understanding the navigation system of Anqi CMS In Anqi CMS, the settings and management of the navigation menu are concentrated in the "Website Navigation Settings" function in the background.This is the core area where you build your website menu

2025-11-09

How to specify an independent template file for content display for a specific category or single page?

In a content management system, we often need to present certain specific content of the website in a unique way, which not only meets the specific needs of branding or marketing, but also brings an optimized browsing experience for visitors.Our CMS is well-versed in this, providing flexible template customization features, allowing us to easily specify a unique template file for a category page, or even a single content page.Why do you need to customize the template for a specific page?

2025-11-09

How to use Tag tags to display related article lists on the page?

In website content operations, how to efficiently organize content, improve user experience, and optimize search engine rankings is a key focus for every operator.AnQiCMS as an enterprise-level content management system provides powerful and flexible functions to meet these needs, among which the Tag label function is an indispensable part.Tag label, simply put, is a keyword or thematic word, which can link scattered article content on a website according to common themes or focus points.Reasonably utilizing Tag tags can not only make it easier for users to discover content of interest

2025-11-09

How to configure and display the global contact information of the website, such as phone number, address, WeChat QR code?

In website operation, clearly and accurately displaying contact information is a key link in building user trust and improving service efficiency.Whether it is a phone number, address, email, or the popular WeChat QR code, AnQiCMS provides a flexible and convenient way to configure and manage these global information to ensure they can be presented efficiently on the website. ### Backend Configuration: Centralize your global contact information To centralize this information, you need to log in to the AnQiCMS admin interface. After logging into the backend, please navigate to the left menu bar of “**Backend Settings**”

2025-11-09