How do the `first` and `last` filters get the first or last element of a string or array?

Calendar 👁️ 60

In Anqi CMS template development, in order to display content more efficiently and flexibly, we often use various filters to process data.These filters are like various small tools in a toolbox, which can help us quickly format, cut or extract data.Today, let's talk about two very practical and intuitive filters:firstandlastHow they help us easily get the first or last element of a string or array.

1. IntroductionfirstandlastFilter

Imagine you are displaying a product list, each product may have a set of images, but you only want to display the first image as the cover on the list page;Or, you have a comment list and want to highlight the latest comment.Or maybe, you need to extract the first or last character from a text for some special design.now,firstandlastThe filter comes into play. Its purpose is to simplify this kind of 'get the head and tail' data operation, making the template code more concise and easy to understand.

2.firstFilter: Quickly get the first element

firstThe function of the filter is clear at a glance: it can get and return the first element from a string or array.

  • Processing strings:If you apply to a stringfirstA filter that returns the first character of the string. It is worth mentioning that the template engine of Anqi CMS supports Chinese well, and if you are dealing with a Chinese string, it will correctly return the first Chinese character instead of a byte.

    Example:

    {{ "AnQiCMS"|first }} {# 显示结果: A #}
    {{ "你好世界"|first }} {# 显示结果: 你 #}
    
  • Handle an array or list:When you have an array or list with multiple elements,firstThe filter will return the first member of this collection. This is very convenient for scenarios that need to display the first item of a list.

    Example:Assumecomplex.commentsIs an array containing comment objects.

    {{ complex.comments|first }} {# 显示结果: 返回数组中的第一个评论对象,通常是其值表示 #}
    

    If it is a simple string array:

    {% set tags = ["CMS", "模板", "运营"] %}
    {{ tags|first }} {# 显示结果: CMS #}
    

When the original string or array is empty,firstThe filter will not return any content, which means you do not have to worry about errors in the template due to empty values.

3.lastFilter: easily get the last element

withfirstCorresponding to the filter,lastThe filter is used to retrieve the last element of a string or an array. It works in a similar way tofirstThe filter works in the opposite direction.

  • Processing strings:For a string,lastThe filter will return its last character. Similarly, for Chinese string, it can also accurately return the last Chinese character.

    Example:

    {{ "AnQiCMS"|last }} {# 显示结果: S #}
    {{ "你好世界"|last }} {# 显示结果: 界 #}
    
  • Handle an array or list:When applied to an array or list,lastThe filter will return the last member of the collection. This is very useful when you need to display the latest or last record.

    Example:Assumecomplex.commentsIt is also an array containing comment objects.

    {{ complex.comments|last }} {# 显示结果: 返回数组中的最后一个评论对象 #}
    

    If it is a simple string array:

    {% set tags = ["CMS", "模板", "运营"] %}
    {{ tags|last }} {# 显示结果: 运营 #}
    

withfirstThe filter behaves similarly, if the original string or array is empty,lastThe filter will not return any content either.

4. Summary

firstandlastThe filter is two small but powerful tools in the Anqi CMS template engine.They can help us extract the information we need most from strings or arrays with great efficiency and clarity - whether it is the first character/element at the beginning or the last one at the end.In daily template development, being proficient in using them can make our code more concise, reduce unnecessary loops and logical judgments, thereby improving development efficiency and the readability of the template.


Frequently Asked Questions (FAQ)

Q1:firstandlastWhat does the filter return when processing an array of complex objects (such as structures)?

A1:When you have an array containing complex objects (such as article objects, product objects, etc. structures),firstorlastThe filter will return the first or last complete complex object instance in this array.It does not automatically extract a specific attribute of the object (such as the title or ID), but returns the object itself.You may need to use dot notation on this basis,{{ obj|first.Title }}) to access the specific properties of the object.

Q2: When the string is Chinese, how do these filters identify and return Chinese characters?

A2:The AnQi CMS template engine has good support for Unicode character sets. When the string is Chinese,firstandlastThe filter can correctly identify each Chinese character as an independent 'character', so it will accurately return the first or last character of the string, rather than producing garbled text or returning only part of the bytes.

Q3: If the variable being processed is neither a string nor an array, or is a null value,firstandlastwhat will the filter return?

A3:

  • Non-string non-array types (such as numbers, boolean values):If you have a single number like5) or a boolean value liketrue)firstorlastFilters, they usually treat them as a 'single-element set containing themselves' and return the value itself directly (for example,{{ 5|first }}will return5,{{ true|last }}will returntrue)
  • null values (nilor empty strings/arrays):If the variable being processed isnil(an empty string,"")or an empty array([])firstandlastThe filter will not return any content and will not throw any errors, making it more robust to use in templates.

Related articles

How does the `fields` filter split a single line string into an array of strings?

During the template development process of AnQi CMS, flexibly handling and displaying data is the key to improving website functionality and user experience.Sometimes, the content we receive from the backend may be a single line string containing multiple pieces of information, such as a list of keywords, product tags, or a set of feature descriptions.If we need to treat this information as separate elements for processing or display, for example, as a list, we would need a method to split this single string into multiple independent items.At this time, the `fields` filter provided by the Anqi CMS template engine can come into play.

2025-11-08

The `safe` filter in Anqi CMS template, when and why to use it to cancel the default escaping of HTML content?

Master the `safe` filter in AnQiCMS templates: unlock the correct rendering and safety boundaries of HTML content AnQiCMS, as an enterprise-level content management system based on Go language, adopts syntax similar to Django template engine in template design, which provides great flexibility for content display.When building website content, we often need to display the information edited on the backend on the front-end page.

2025-11-08

How to enable or disable automatic escaping for specific code blocks in templates using the `autoescape` tag?

In AnQi CMS template development, how to balance flexibility and security when handling dynamic content is an important consideration.Amongst, the HTML automatic escaping mechanism (`autoescape`) plays a key role, which is aimed at preventing cross-site scripting (XSS) attacks, while also allowing us to display native HTML content when needed.Understand and master the usage of the `autoescape` tag, which will make your template creation more skillful.Understanding automatic escaping

2025-11-08

What security escaping features do the `escape`, `e`, and `escapejs` filters provide when outputting HTML or JavaScript code?

It is crucial for the safety of output content in website operations.Especially when displaying user-submitted data or information obtained from external sources, if not properly processed, websites are easily vulnerable to cross-site scripting attacks (XSS) and other threats.AnQiCMS as a content management system that focuses on security, provides a powerful security escaping mechanism at the template rendering level, among which the `escape`, `e`, and `escapejs` filters are the key tools to ensure output security.AnQiCMS's template engine draws inspiration from Django

2025-11-08

How to precisely control the decimal place display of floating-point numbers using the `floatformat` filter, including positive and negative digit settings?

In website content operations, accurately displaying numbers, especially floating-point numbers, is often a key factor affecting user experience and data professionalism.It is crucial to ensure that numbers are presented consistently and legibly in product prices, statistical data, or scientific reports.AnQiCMS (AnQiCMS) is well aware of this need, providing a powerful `floatformat` filter in the template engine to allow content creators to flexibly control the display precision of floating-point numbers.### `floatformat` filter

2025-11-08

How does the `get_digit` filter retrieve a digit from a number at a specified position?

In the AnQi CMS template world, flexible handling and displaying data is a key link in content operation.When faced with the need to accurately extract a specific digit from a sequence of numbers, the `get_digit` filter is a very practical tool.It can help us achieve some detailed display requirements, such as grouping or highlighting based on the specific position of numbers. ### Core Function and Usage The main function of the `get_digit` filter, as the name implies, is to obtain a single digit from a number at a specific position.

2025-11-08

How does the `index` filter find the first occurrence of a keyword in a string or array?

In AnQi CMS template development, we often need to fine-tune the display of content, which includes flexible handling of string and array content.Understand and make good use of the various template filters provided by Anqi CMS, which can greatly enhance our ability to build dynamic and intelligent websites.Today, let's delve into a very practical filter——`index`, which can help us accurately locate the first occurrence of a keyword in a string or array.### `index` filter: A powerful tool for precise keyword positioning Imagine that

2025-11-08

How do the `integer` and `float` filters convert strings to integers or floating-point numbers and handle conversion failure situations?

In web template development, flexible handling of data types is the key to ensuring correct content display.We often encounter situations where we need to convert string data obtained from databases or external interfaces into numbers for calculation or formatting display.AnQiCMS (AnQiCMS) fully considers this requirement, providing two built-in filters `integer` and `float` to help users easily convert strings to integers or floating-point numbers, and intelligently handle conversion failure cases, thereby enhancing the robustness of the template.

2025-11-08