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.