How to get the total number of categories returned by `categoryList` to control the page layout or display the 'All' option?

Calendar 👁️ 48

In AnQi CMS template development, the category list (categoryListThe closing tag is one of the core tools for organizing website content and building navigation.It can help us easily display the classification structure of articles, products, and other content.However, in practical applications, we may not only need to display the categories themselves, but also need to flexibly adjust the page layout based on the number of categories, or decide whether to display an 'All' option so that users can browse the content under all categories.

Then, how can wecategoryListWhere can I get the total number of categories in the returned category list and use it to control the display logic of the page? Next, we will delve into this practical skill.

UnderstandingcategoryListLabel and its returned data

First, let's reviewcategoryListThe basic usage of the tag. The main function of this tag is to obtain the classification list of the website, we can go throughmoduleIdThe parameter specifies which type of content model classification to retrieve (for example, article model ID is 1, product model ID is 2), throughparentIdParameters to retrieve child categories under a parent category, or byparentId="0"Get the top-level category.

When we use{% categoryList categories with moduleId="1" parentId="0" %}This method of invoking the tag will return a namedcategoriesThe array object. This array contains all the classification information that meets the conditions, such as each category's ID, title, link, etc.The key to obtaining the total number of categories lies in how to operate thiscategoriesarray.

Method to get the total number of category lists

In Anqi CMS template engine, there are several ways to easily obtaincategoryListThe total number of categories returned by the tag:

  1. Utilizeforin the loopforloop.LengthpropertyWhen we are inforTraverse in a loopcategoriesan array,forloopThis built-in object automatically provides some information about the current loop, includingforloop.Lengthwhich indicates the total length of the array being cycled.

    {% categoryList categories with moduleId="1" parentId="0" %}
        {% if categories %} {# 首先判断列表是否为空 #}
            {% for item in categories %}
                {# 这里的 forloop.Length 就是分类列表的总数 #}
                <p>当前分类总数:{{ forloop.Length }}</p>
                <p>分类名称:{{ item.Title }}</p>
            {% endfor %}
        {% endif %}
    {% endcategoryList %}
    

    This method is very intuitive, especially suitable for the case where you are already categorizing lists in a loop and need to use the total number inside the loop.

  2. UselengthFilter lengthA filter provided by Anqi CMS template engine is a general-purpose filter that can be used to obtain the length of strings, arrays, or key-value pairs. ForcategoryListreturnedcategoriesarrays, we can use it directly.lengthA filter to get the total without entering a loop.

    {% categoryList categories with moduleId="1" parentId="0" %}
        {% set categoryCount = categories|length %}
        <p>分类列表总数:{{ categoryCount }}</p>
    {% endcategoryList %}
    

    This method is more flexible because it canforGet the total directly outside the loop, which is very suitable for situations where you need to know the total in advance, such as layout control. To keep the code neat, we usually assign it to a temporary variable (such ascategoryCount),convenient for subsequent use.

Actual application: control page layout and 'All' option

After understanding how to get the total number of categories, we can apply it to the actual page design.

Scene one: Dynamically adjust the page layout based on the number of categories

Suppose we have a category navigation area, if the number of categories is less than 5, we hope they display horizontally; if more than 5, it may be necessary to display a 'More' button or use a two-column or more layout.

{% categoryList categories with moduleId="1" parentId="0" %}
    {% set categoryCount = categories|length %}

    {% if categoryCount > 5 %}
        <div class="category-nav-complex">
            {# 复杂的布局,例如多列或者带滚动条的布局 #}
            <p>当前有 {{ categoryCount }} 个分类,采用复杂布局。</p>
            <ul>
                {% for item in categories %}
                    <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
                {% endfor %}
            </ul>
        </div>
    {% else %}
        <div class="category-nav-simple">
            {# 简单的布局,例如横向平铺 #}
            <p>当前有 {{ categoryCount }} 个分类,采用简洁布局。</p>
            <ul>
                {% for item in categories %}
                    <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
                {% endfor %}
            </ul>
        </div>
    {% endif %}
{% endcategoryList %}

Scenario two: Dynamically display the "All" option

In many category lists, we hope to provide a "All" option before all specific categories, which can be clicked to view the content under all categories.But if the website itself only has one category, or has no category at all, then the 'All' option may seem unnecessary.By obtaining the total number of categories, we can intelligently control the display of the 'All' option.

<div class="category-filter-bar">
    {% categoryList categories with moduleId="1" parentId="0" %}
        {% set categoryCount = categories|length %}

        {# 只有当存在多个分类时,才显示“全部”选项。或者即使只有一个分类,也希望显示“全部” #}
        {% if categoryCount > 1 or categoryCount == 1 %} {# 可以根据实际需求调整这里的条件 #}
            <a href="/archive/list.html" class="{% if currentCategoryId == 0 %}active{% endif %}">全部</a>
        {% endif %}

        {% for item in categories %}
            <a href="{{ item.Link }}" class="{% if currentCategoryId == item.Id %}active{% endif %}">{{ item.Title }}</a>
        {% endfor %}
    {% endcategoryList %}
</div>

In this example,currentCategoryIdAssuming it is the category ID of the current page, when it is 0, it indicates that the user is browsing all content. BycategoryCountThe judgment, we can make the "All" option appear only when it is meaningful, to avoid page redundancy.

ObtaincategoryListThe total number of categories returned is a simple yet very useful trick. Whether it is to better control the page layout or to provide smarter user interaction, masteringforloop.LengthorlengthFilters can make your Aiqi CMS website template more flexible and adaptable.By these methods, you can make the website content more closely match the user's needs, providing a smoother browsing experience.

Frequently Asked Questions (FAQ)

  1. forloop.Lengthand|lengthWhat are the differences between filters? forloop.LengthisforA special variable used inside the loop, which can only get the total length of the current loop list in each iteration.|lengthThe filter can be applied to any array, string, or key-value pair object, regardless of whether it is insidefora loop, it can directly obtain the length of the object. In short,forloop.LengthWith context constraints,|lengthThe filter is more general.

  2. How to judgecategoryListIs the returned list empty?You can useifLabel direct judgmentcategoriesDoes the variable exist or is its length greater than 0. For example:

    {% categoryList categories with moduleId="1" parentId="0" %}
        {% if categories %} {# 判断categories是否存在且不为空 #}
            {# 列表不为空时的处理逻辑 #}
        {% else %}
            {# 列表为空时的处理逻辑 #}
        {% endif %}
    {% endcategoryList %}
    

    Or use:|lengthFilter:

    {% categoryList categories with moduleId="1" parentId="0" %}
        {% if categories|length > 0 %}
            {# 列表不为空时的处理逻辑 #}
        {% else %}
            {# 列表为空时的处理逻辑 #}
        {% endif %}
    {% endcategoryList %}
    
  3. In addition to the total,categoryListWhat useful information can be provided to control the display of the page? categoryListEach category object returned by the tag (item) Contains many useful properties, such asitem.Id(Category ID),item.Title(Category Title),item.Link(Category Link),item.Description(Category Description),item.HasChildren(Has Subcategories),item.IsCurrent(Whether the current category) and so on. You can further refine the page display logic based on these properties, such as judgingitem.HasChildrento decide whether to display the secondary menu or judgeitem.IsCurrentAdd an active style for the current category.

Related articles

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

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 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 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 does AnQiCMS manage the display of content for different brands or sub-sites uniformly?

In today's complex network environment, many enterprises or individuals need to manage multiple brand sites, product line special theme sites, or regional sub-sites.How to efficiently and uniformly manage the massive content of these sites to ensure that each site has a unique brand image and content display, which has become a major challenge for operators.AnQiCMS is a powerful content management system dedicated to solving this problem, it makes it easy and convenient to manage the unified content display of multiple brands or sub-sites through its unique design concept and rich features.### Unified Management

2025-11-08

How to customize the content structure according to business requirements and display it on the front end?

In the daily operation of websites, we often encounter such needs: standard content structures, such as articles and products, cannot fully meet the unique display requirements of our business.It may be necessary to add 'author source' and 'publishing organization' fields for a specific type of information, or to add 'size' and 'material' and other personalized attributes for a product series.AnQiCMS (AnQiCMS) provides high flexibility in content management, allowing us to customize the content structure according to actual business scenarios and display it accurately on the front end. Next

2025-11-08

How does AnQiCMS support the switching of multilingual content on the page?

In today's globalized digital world, website multilingual support has become a key step for enterprises and content operators to expand into international markets and serve diverse user groups.AnQiCMS as an efficient enterprise-level content management system, fully considers this requirement, and provides a flexible and practical multi-language content switching display solution.AnQiCMS' multi-language strategy lies in its powerful multi-site management function and the flexible calling mechanism of the front-end template.It does not simply provide content automatic translation, but encourages providing carefully planned, independently maintained localized content for users of different languages

2025-11-08

How to optimize URL structure through pseudo-static configuration to improve the display of content in search results?

In today's digital world, the visibility of websites is crucial for the dissemination of content and the growth of business.Search engine optimization (SEO) is one of the core strategies for improving website visibility, and URL structure optimization is a key element that cannot be ignored in SEO.A well-designed, easy-to-understand URL structure, which not only helps search engines better crawl and understand your content, but also significantly improves user experience, thereby enhancing the display effect of the content in search results.As a content management system designed specifically for content operators

2025-11-08