How to use the `first` and `last` filters to quickly get the title of the first or last article in the Anqi CMS article list?

Calendar 👁️ 71

In website operation, we often need to quickly extract some specific information from the article list, such as the home page may need to display the latest article title, or in some special modules, we need to obtain the title of the first or last item in the article list.AnQiCMS (AnQiCMS) can easily meet these needs with its flexible template engine and rich filter functions.

The AnqiCMS template system borrows the syntax of mainstream template engines like Django, allowing developers and operators to process data and control page logic through concise and intuitive tags and filters. Filters are an important part of template variable processing, enabling the transformation, formatting, or extraction of specific information, and the syntax is usually expressed as{{ 变量 | 过滤器名称: 参数 }}.

Core Tool:firstandlastFilter

Among the many filters provided by AnqiCMS,firstandlastthe filter is a powerful assistant for processing list data.

  1. firstFilterAs the name implies,firstThe filter is used to extract the first element from a sequence (such as a string, array, or list).If applied to a string, it will return the first character of the string;If applied to an array or article list, it will return the first complete object in the list.
  2. lastFilterwithfirstThe filter is relative,lastThe filter is used to extract the last element from a sequence. Similarly, when applied to a string, it returns the last character, and when applied to an array or list of articles, it returns the last complete object in the list.

These filters greatly simplify our work of locating and obtaining data at the ends of the list without manually traversing the entire list.

Get article list:archiveListTag

To applyfirstandlastThe filter requires an article list as the operation object first. In AnqiCMS,archiveListTags are the core tools for obtaining article lists. They can flexibly query articles based on various conditions such as category ID, module ID, sorting method, and display quantity.

For example, we can retrieve the latest 10 articles in the following way and store the results in a namedarticles:

{% archiveList articles with type="list" limit="10" order="id desc" %}
    {# 列表内容通常在这里循环显示,但为了获取首尾文章,我们只需获取列表本身 #}
{% endarchiveList %}

here,type="list"This means to get a list without pagination,limit="10"Limited to 10 articlesorder="id desc"Ensuring we get the latest articles.

Practical exercise: Quickly obtain the titles of the first and last articles

Got the list of articlesarticlesAfter the variable, we can combinefirstandlastUse the filter to get the required information

First step: Make sure the article list exists

Before trying to get the articles in the list, it is best to check firstarticlesIs the variable empty to avoid template errors when the list is empty.

{% if articles %}
    {# 文章列表存在,可以继续操作 #}
{% else %}
    <p>当前没有任何文章。</p>
{% endif %}

Step two: ApplyfirstandlastFilter and get the title

IfarticlesThe list has content,articles|firstThe first article object in the list will be returned,articles|lastIt returns the last article object. The article object typically containsTitle(Title),Link(Link),Description(description) and other properties. We just need to use the dot operator.) to access these properties.

For example, to get the title of the first article:

{% set firstArticle = articles|first %}
{% if firstArticle %}
    <h3>最新文章:<a href="{{ firstArticle.Link }}">{{ firstArticle.Title }}</a></h3>
{% endif %}

Similarly, to get the title of the last article:

{% set lastArticle = articles|last %}
{% if lastArticle %}
    <h3>最旧文章:<a href="{{ lastArticle.Link }}">{{ lastArticle.Title }}</a></h3>
{% endif %}

Complete code example

Combine the above steps and you can quickly retrieve and display the first and last titles of the article list in the template:

{# 1. 获取最新发布的 10 篇文章列表 #}
{% archiveList articles with type="list" limit="10" order="id desc" %}
{% endarchiveList %}

{# 2. 检查文章列表是否存在内容 #}
{% if articles %}
    {# 获取列表中的第一篇文章对象 #}
    {% set firstArticle = articles|first %}
    {# 获取列表中的最后一篇文章对象 #}
    {% set lastArticle = articles|last %}

    <div class="article-summary">
        {% if firstArticle %}
            <p><strong>最新文章:</strong>
                <a href="{{ firstArticle.Link }}">{{ firstArticle.Title }}</a>
            </p>
        {% endif %}

        {% if lastArticle %}
            <p><strong>最早文章(此列表内):</strong>
                <a href="{{ lastArticle.Link }}">{{ lastArticle.Title }}</a>
            </p>
        {% endif %}
    </div>

    {# 如果需要,这里可以继续循环显示完整的文章列表 #}
    <ul class="article-list">
        {% for article in articles %}
            <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
        {% endfor %}
    </ul>

{% else %}
    <p>抱歉,目前没有找到任何文章。</p>
{% endif %}

In this way, we can efficiently obtain the title of the first or last article in the article list with just a few lines of concise code in the AnqiCMS template, which provides great convenience for implementing the latest dynamic, featured content display, or quick navigation functions.It not only makes template code easier to maintain, but also improves the flexibility of content display.


Frequently Asked Questions (FAQ)

Q1: Can I get other information about the article besides the title? For example, the link or thumbnail?A1: Of course you can.firstandlastThe filter returns the complete article object. This means that you can use the dot operator to access properties of the object..Access any available attributes of the article object, such as{{ firstArticle.Link }}Used to obtain the link,{{ firstArticle.Thumb }}Used to obtain the thumbnail,{{ firstArticle.Description }}Used to obtain the description, etc. Just based onarchiveListtagged in the documentation.itemField, replace.TitleJust do it.

Q2: If the article list is empty, usefirstorlastWill the filter throw an error?A2: Use the filter directly on an empty listfirstorlastThe filter usually will not throw an error directly, but the result returned will benil(Empty value). If incorrectnilCheck the value before directly accessing its properties (for example{{ nil.Title }}), it may cause template rendering errors. Therefore, it is strongly recommended to usefirstArticleorlastArticlebefore using the variable{% if firstArticle %}or{% if lastArticle %}Check to ensure that the variable indeed contains a valid article object.

Q3: I can use it within the loop of the article list.firstandlastDoes the filter determine whether the current article is the first or last?A3: For example, within the loop,{% for article in articles %}In fact, it is theoretically also possible to use the entirearticleslist again.firstorlastThe filter is used for comparison, but this is not the most recommended approach. A more concise and efficient way is to use loop variables.forloopsuch as the provided properties,{% if forloop.first %}(Determine if it is the first article in the loop) and{% if forloop.last %}(Determine if it is the last article in the loop).firstandlastThe filter is more suitable for use in loopsother thanTo independently obtain the first and last elements of the list.

Related articles

In Anqi CMS template, how does the `random` filter implement the random selection of an element from an array or string to display and enhance the dynamic nature of the content?

Make the Anqi CMS website content vivid: explore the `random` filter, and uncover the mystery of dynamic display In the era of information explosion, an efficient and flexible website content management system is an indispensable tool for operators.The AnQi CMS is a system developed based on the Go language, dedicated to providing a high-performance, easily scalable content management solution. It uses a syntax similar to the Django template engine in template design, greatly simplifying the complexity of development and content presentation.But besides content publishing, we all hope that the website can maintain its freshness

2025-11-08

How to implement `striptags` and `removetags` filters in Anqicms, one for removing all HTML tags and another for removing specified tags?

In Anqi CMS, we often encounter scenarios where we need to handle HTML tags.To ensure the purity of content, meet display requirements, or ensure safety, it is an important ability to flexibly control HTML tags.AnQiCMS's powerful template engine provides the `striptags` and `removetags` filters, which are very useful and can help us easily remove all HTML tags or only remove specified tags.Next, we will delve into how these two filters work together

2025-11-08

How to use the `yesno` filter to output custom text such as 'Enabled/Disabled/Pending' based on the boolean value or the existence of a field returned by the Anqi CMS backend?

In website operation, we often need to display corresponding text prompts on the front page according to the status of the content, such as whether it is enabled, recommended, or online.Directly outputting the boolean value `true` or `false` returned by the backend may not be intuitive and friendly.The AnQiCMS template engine provides a simple yet powerful tool - the `yesno` filter, which can help us elegantly convert boolean values or field existence states into easily understandable custom text, such as "Enabled/Disabled/Pending"}

2025-11-08

The `addslashes` filter in AnQi CMS, how to escape a string that may contain special characters to safely insert into JS or HTML attribute values?

In the daily operation of Anqi CMS, we often need to display the dynamic content stored in the database on the front end of the website.This content may come from user input, data scraping, or other channels, and it is inevitable that it will contain some special characters.If these special characters are not handled properly and directly inserted into JavaScript code or HTML attribute values, it may cause page layout chaos, functionality failure, and even serious security risks, such as cross-site scripting attacks (XSS).

2025-11-08

What are the application scenarios and encoding differences of the `urlencode` and `iriencode` filters in the AnQi CMS template when encoding URL parameters?

In AnQiCMS template development, when handling URL parameters, we often encounter the need to encode them.This is mainly to ensure the legality of the URL, avoid special characters from destroying the URL structure, and correctly transmit data containing non-ASCII characters (such as Chinese).AnQiCMS provides the `urlencode` and `iriencode` filters to help us complete this task, but their application scenarios and encoding differences are not the same.

2025-11-08

How to use the `linebreaks` and `linebreaksbr` filters to convert newline characters in the plain text content entered by an Anqie CMS user into HTML `<p>` or `<br>` tags?

In a content management system, processing plain text content entered by users and displaying it on the web page in the expected format is a common requirement.When the user enters text with line breaks in the back-end editor, the browser does not default to rendering it as HTML line breaks.All content may be squeezed onto one line, causing disordered layout and affecting reading experience.Fortunately, AnQiCMS provides a convenient template filter to solve this problem.

2025-11-08

How to automatically add line numbers to code blocks or list content in `linenumbers` filter in Anqie CMS to enhance readability?

In daily content creation and website operations, we often need to insert code examples, configuration lists, or detailed operation steps in articles.The characteristic of this content is that it is multi-line text, and if line numbers can be automatically added to it, it will greatly enhance the reader's reading experience and the professionalism of the content.Imagine when you need to explain a part of the code to the reader, or guide them to complete a complex setup, you can accurately mention 'See line 5 of the code' or 'In step 3', this improvement in communication efficiency is self-evident.

2025-11-08

How to use `integer` and `float` filters to convert string numbers in Anqi CMS templates to numeric types that can be used in mathematical operations?

During the development of Anqi CMS templates, we often encounter scenarios where we need to perform numerical operations, such as calculating the total price of goods, comparing inventory quantities, or displaying different content based on specific values.However, sometimes the data obtained from the background, even if it looks like a number, may exist in the template as a string, which prevents us from performing mathematical operations directly.

2025-11-08