How to get and display all articles under a specified category in AnQiCMS template?

When building a website in AnQiCMS, we often need to display article lists according to specific content categories, whether it is blog categories, product categories, or news categories.This not only helps in organizing the website content, but also enhances the user browsing experience and the friendliness to search engines.AnQiCMS provides powerful and flexible template tags, making this requirement simple and intuitive.

AnQiCMS template system adopts syntax similar to the Django template engine, with Go language as the underlying support, ensuring the efficiency of template parsing. In template files, we usually use double curly braces{{变量}}To output variable content, use single curly braces and percent signs{% 标签 %}To call functional tags, such as conditional judgment and loop control. All template files are stored uniformly in/templateThe content is in the directory and encoded in UTF-8, ensuring correct display.

Core tags:archiveListDeep analysis

AnQiCMS is the core to obtain and display the list of all articles under a specified category.archiveListThe tag is specifically used for querying and outputting the document list under different content models. Understanding its parameters is the key to successfully achieving the goal.

archiveListThe basic usage of the tag is as follows:{% archiveList 变量名称 with 参数1="值1" 参数2="值2" %}...{% endarchiveList %}In which, 'variable name' is a temporary variable we define for the article list we obtain, usually namedarchivesfor convenience inforthe loop.

The following are some examples of usingarchiveListCommonly used key parameters:

  1. moduleId(Model ID):In AnQiCMS, articles, products, etc. all belong to different "content models".Each model has a unique ID.moduleId="1"(Specific ID can be found in the background under "Content Management" -> "Content Model"). This is because the category is attached to a specific content model.
  2. categoryId(Category ID):This is the core parameter to specify which category of articles to retrieve. You can pass a specific category ID, such ascategoryId="10"If you need to get articles of multiple categories, you can use commas to separate multiple IDs, such ascategoryId="10,11,12"It is worth noting that if you do not specify this parameter on the category list page (i.e., the category ID is already included in the URL),archiveListThe system will automatically try to read the category ID of the current page. If you want to avoid this automatic reading behavior, you can explicitly setcategoryId="0".
  3. type(List type):This parameter determines the display method of the article list.
    • type="list": Used to obtain a fixed number of article lists,配合limitparameters.
    • type="page": Used to obtain article lists that support pagination, usually withpaginationTag combination usage to display page navigation.
  4. limit(Display Quantity):Whentype="list"This parameter specifies the number of articles to be displayed, for example,limit="10"It indicates displaying 10 articles. It also supportsoffset,countpattern, such aslimit="2,10"[en]Displaying 10 articles starting from the 3rd article (skipping the first 2).
  5. order[en](Sorting method):[en]We can sort articles according to different requirements. Common sorting values include:
    • id desc:Arrange articles in descending order by article ID (the most recently published articles first).
    • views desc:Arrange articles in descending order by views (the most popular articles first).
    • sort desc:Sorted in descending order according to the custom sorting value set in the background.
  6. child(Whether to include subcategories):By default,childparameter astrueindicates retrieving articles under the specified category and all its subcategories. If you only want to display articles under the current specified category without including subcategories, you can set it tochild=false.
  7. siteId(Site ID):If your AnQiCMS has multiple sites deployed and you want to access data from other sites, you can specify this parameter. Generally, it does not need to be set.

WhenarchiveListTags obtain the article list and then it assigns it to the variable you defined (for examplearchives), which is an array object. In the template, you can use{% for item in archives %}to iterate over this array,itemrepresents each article in the array.

Each article(item)object contains the following common fields:

  • Id: Article ID
  • Title: Article title
  • Link: Article detail page link
  • DescriptionArticle summary
  • Content: Article content (usually used on detail pages, while the list page generally only shows a brief introduction)
  • CategoryId:Article category ID
  • ViewsArticle views
  • CreatedTime【en】:Article publish time (timestamp format, needs to be used)stampToDateTag formatting)
  • Thumb:Article thumbnail address
  • Logo【en】:Article cover first image address
  • as well as other fields customized in the 'Content Model'.

Practical Exercise: Retrieve and display the article list

UnderstoodarchiveListAfter the various parameters of the tag, let's look at several actual application scenarios.

Scenario one: Display the latest article list under a fixed category (no pagination)

Assuming we want to display the latest 5 articles of the "Company News" category (category ID 5, belongs to the Article model, model ID 1) in a block on the homepage.

<div class="news-section">
    <h2>公司新闻</h2>
    <ul>
        {% archiveList archives with moduleId="1" categoryId="5" order="id desc" limit="5" %}
            {% for item in archives %}
            <li>
                <a href="{{ item.Link }}">
                    <img src="{{ item.Thumb }}" alt="{{ item.Title }}" {% if not item.Thumb %}style="display:none;"{% endif %}>
                    <h3>{{ item.Title }}</h3>
                    <p>{{ item.Description|truncatechars:80 }}</p> {# 截取80个字符并添加... #}
                    <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                    <span>阅读量:{{ item.Views }}</span>
                </a>
            </li>
            {% empty %}
            <li>暂无新闻文章。</li>
            {% endfor %}
        {% endarchiveList %}
    </ul>
</div>

Code analysis:

  • moduleId="1":Specify the content we want to retrieve under the article model.
  • categoryId="5":Explicitly specify to only retrieve articles with category ID 5.
  • order="id desc":Ensure the articles are sorted in descending order by article ID, meaning the most recently published are at the top.
  • limit="5"Limit to displaying the latest 5 articles only.
  • {% for item in archives %}Loop through each article obtained.
  • {{ item.Thumb }}Output the article thumbnail.{% if not item.Thumb %}style="display:none;"{% endif %}It is a little trick to hide the image tag when there is no thumbnail.
  • {{ item.Title }}/{{ item.Link }}/{{ item.Description }}/{{ item.Views }}Output the article title, link, introduction, and view count.
  • {{ stampToDate(item.CreatedTime, "2006-01-02") }}:CreatedTimeIs a timestamp, we usestampToDateThe tag to format it as a date in the format of “year-month-day”.
  • {{ item.Description|truncatechars:80 }}Use a filter to truncate the article summary to 80 characters and automatically add an ellipsis.
  • {% empty %}IfarchivesIf it is empty (i.e., there are no articles), it will display “No news articles available.”.

Scene two: Display the article list on the category list page with pagination support

When accessing a category page, we want to display all articles under that category and provide pagination functionality. In this case, it is usually not necessary to manually specifycategoryId,archiveListIntelligently identifies the current page's category ID.

<div class="article-list-container">
    <h1>{% categoryDetail with name="Title" %}</h1> {# 显示当前分类的标题 #}

    <ul class="article-list">
        {% archiveList archives with type="page" moduleId="1" order="id desc" limit="10" %}
            {% for item in archives %}
            <li>
                <a href="{{ item.Link }}">
                    <img src="{{ item.Thumb }}" alt="{{ item.Title }}" {% if not item.Thumb %}style="display:none;"{% endif %}>
                    <h2>{{ item.Title }}</h2>
                    <p>{{ item.Description }}</p>
                    <div class="meta-info">
                        <span>发布于:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                        <span>阅读:{{ item.Views }}</span>
                    </div>
                </a>
            </li>
            {% empty %}
            <li>当前分类暂无文章。</li>
            {% endfor %}
        {% endarchiveList %}
    </ul>

    {# 分页导航 #}
    <div class="pagination-nav">
        {% pagination pages with show="5" %}
            <ul>
                <li {% if pages.FirstPage.IsCurrent %}class="active"{% endif %}><a href="{{ pages.FirstPage.Link }}">首页</a></li>
                {% if pages.PrevPage %}<li class="prev"><a href="{{ pages.PrevPage.Link }}">上一页</a></li>{% endif %}
                {% for page_item in pages.Pages %}
                    <li {% if page_item.IsCurrent %}class="active"{% endif %}><a href="{{ page_item.Link }}">{{ page_item.Name }}</a></li>
                {% endfor %}
                {% if pages.NextPage %}<li class="next"><a href="{{ pages.NextPage.Link }}">下一页</a></li>{% endif %}
                <li {% if pages.LastPage.IsCurrent %}class="active"{% endif %}><a href="{{ pages.LastPage.Link }}">末页</a></li>
            </ul>
        {% endpagination %}
    </div>
</div>

Code analysis:

  • <h1>{% categoryDetail with name="Title" %}</h1>: UsecategoryDetailGathers and displays the title of the current category, so the user knows which category they are browsing.
  • type="page"Activates the pagination feature.
  • limit="10"[en]: Displaying 10 articles per page.
  • {% pagination pages with show="5" %}[en]: This is the core of pagination. It generates apagesAn object that contains all the information needed for pagination (total pages, current page, first page, last page, previous page, next page, and a list of middle page numbers).show="5"Indicates that the middle page numbers can display a maximum of 5.
  • By traversingpages.Pages, we have built page number links, and useIsCurrentproperty to determine the current page number, so thatactivestyles can be added.

Summary and **Practice

Retrieve and display the list of articles under a specified category in AnQiCMS, mainly revolving aroundarchiveListBy flexibly usingmoduleId/categoryId/type/limitandorderWith parameters, you can easily achieve various content display needs. CombinedstampToDateformat time, as well aspaginationTag implementation enables pagination, building a dynamic content area with comprehensive functionality and good user experience.

Some **practical suggestions:**

  • ClearmoduleIdandcategoryId:When designing a template, first determine the content model ID and category ID you want to operate.
  • Pay attention to the case:AnQiCMS template tags and parameters are case-sensitive, make sure the spelling is correct.
  • Handle empty data:Use{% empty %}or clause{% if %}Condition to handle the case without articles elegantly, avoiding the page from displaying blank or reporting errors.
  • Make good use of filters:When displaying article summaries on the page, usetruncatecharsortruncatewordsFilters can effectively control the length of text and keep the page tidy.
  • Image processing:When displaying article thumbnails, judgeitem.ThumbWhether there is to avoidsrcBrowser error or style issues caused by empty properties.

With these techniques, you can fully utilize the template function of AnQiCMS to create rich and diverse content display pages.


Frequently Asked Questions (FAQ)

Q1: How can I display a list of articles with different content models on a single page? A1:You can do this by calling multiple timesarchiveListtags, and specify a different one each time you callmoduleIdImplement the parameter. For example, you can call `archiveList` once