How to display the first or last word of a string in AnQiCMS template?

Calendar 👁️ 79

In website content operation, we often need to finely control the displayed information.Sometimes, a title may be very long, and we only want to display the first word in a specific area, or highlight the last word for some design needs.AnQiCMS (AnQiCMS) provides a powerful and flexible template engine, drawing on the essence of Django template syntax, allowing us to achieve these seemingly complex text processing needs through simple filters (Filters).

Today, let's talk about how to cleverly extract and display the first or last word of a string in the AnQiCMS template.

Understand the core tool: Filter

In AnQiCMS templates, filters are used to modify the display content of variables. They are through|The symbol is connected after the variable name. To extract the first or last word, we need to combine several key filters:

  1. splitFilterThis filter can split a string into an array of words (or substrings) based on the delimiter you specify.
  2. firstFilterIt is used to get the first element of an array.
  3. lastFilterUsed to get the last element of the array.

With these tools, we can combine the desired functions like building blocks.

Get the first word of the string.

Suppose we have a namedarticle.TitleThe variable contains the full title of an article, for example: "AnQi CMS: Providing Efficient Solutions for Your Enterprise-Level Website".We hope to only display the first word of the title "AnQi CMS".

First, we need to split this complete title string into individual words. At this point,splitthe filter comes into play. We can write it like this:

{{ article.Title|split:" " }}

This line of code will return an array containing all words, for example["安企CMS:", "为您的", "企业级网站", "提供高效解决方案"]Please note that if the first "word" in the title contains punctuation,split:" "it will be treated as part of the word by default.

Next, we just need to take the first element from this array of words. We can directlyfirsta filter tosplitput it on the result of the filter. The full syntax is:

{{ (article.Title|split:" ")|first }}

This will display on the page, such as “AnQiCMS:”. If your title is all English, such as “AnQiCMS: Efficient Solutions for Your Enterprise Website”, then|split:" "after,|firstWill get "AnQiCMS:".

Get the last word of the string

Similarly, if we want to get the last word 'solution' from the title 'AnQi CMS: Provide an efficient solution for your enterprise-level website', the operation process is also very similar.

We still need to use firstsplitThe filter splits the title into an array of words:

{{ article.Title|split:" " }}

After getting the array, this time we no longer choose the first one, but the last element. At this point,lastThe filter is very suitable. The complete code would be:

{{ (article.Title|split:" ")|last }}

Thus, the page will display the "Solution".

Actual application scenarios and some tips

This function of extracting specific words from strings is very useful in website construction:

  • Dynamic title abbreviationIn a card-style list, sidebar, or navigation menu, if the full title is too long, the first word can be dynamically displayed as a summary.
  • Highlight the key pointsIn marketing copy, sometimes the last word is deliberately made the core keyword, and this method can be styled separately to make it more prominent.
  • SEO optimizationIn some layouts, it may be necessary to use a part of the title as microcopy or alt text, keeping it concise.

Handling empty string or single-word cases:If you are concerned about the variablearticle.TitleMay be empty, or contain only a word, the above method still works well. If the string is empty,split:" "an empty array will be returned, at this timefirstorlastNothing will be output. If the string contains only one word,split:" "it will return an array containing only that word,firstandlastit will return this unique word correctly.

Handle existing HTML tags:If your string content may contain HTML tags (for example, the title is obtained from a rich text editor), and you want to remove these tags before extracting words, you can usestriptagsa filter. For example:

{{ ((article.Title|striptags)|split:" ")|first }}

This ensures that you get pure text words and not fragments with HTML tags.

Set the default value:To enhance user experience, to prevent in some extreme cases (such asarticle.TitleVariable does not exist or is empty) The page appears blank, you can combinedefaulta filter to provide an alternative text:

{{ (article.Title|split:" ")|first|default:"无标题" }}

In this way, if the first word cannot be extracted, 'No Title' will be displayed on the page.

By combining these simple filters, Anqi CMS provides great convenience to content operators, allowing us to control the display of content more flexibly and accurately.


Frequently Asked Questions (FAQ)

1. If my string content is purely Chinese, for example “Anqi Content Management System”, thensplit:" "Can it split the words correctly?For continuous Chinese text,split:" "The entire string is treated as a 'word' because there are no spaces between Chinese characters. If you want to treat each Chinese character as an independent 'word', you need to usemake_listA filter that splits a string into an array of individual characters. For example{{ ("安企内容管理系统"|make_list)|first }}It will output '安'.

2. Can I use characters other than spaces to separate strings?Of course you can.splitThe filter is very flexible, you can specify any character you want as a delimiter. For example, if your keyword list is "SEO, marketing, website", you can get the first keyword in this way: {{ ("SEO,营销,建站"|split:",")|first }}This will get 'SEO'.

3. How to ensure that the extracted words are plain text and not fragments with HTML tags?If the original string may contain HTML tags (for example, the title is obtained from a rich text editor), it is recommended to usesplitthe filter beforestriptagsfilter.striptagsRemove all HTML and XML tags from the string, leaving only plain text content.In this way, during the subsequent word segmentation and extraction, it can ensure that pure text words are obtained. For example: {{ ((article.Content|striptags)|split:" ")|first }}.

Related articles

What effect will be produced when the `wordcount` filter is combined with the `add` filter?

AnQiCMS with its flexible and powerful template system makes the presentation and data processing of website content very efficient.In the process of template development, skillfully combining various filters often unlocks unexpected practical effects.Today, let's delve deeply into two seemingly basic filters that, when combined, can produce wonderful effects: `wordcount` and `add`.

2025-11-09

In AnQiCMS content management, after batch replacing keywords, will the `wordcount` result be automatically updated?

In content management, efficiency and accuracy are the core concerns of operators.AnQiCMS is a feature-rich CMS that provides various tools to simplify content maintenance.Among them, the batch keyword replacement function greatly improves the efficiency of content adjustment, while word count (`wordcount`) is an important indicator of content length.Around these two features, users often wonder: Will the word count automatically update after the content has been replaced with batch keywords?

2025-11-09

How to use the `fields` filter to extract all 'words' from a string and further process them?

In AnQiCMS, content operators often need to flexibly handle and display text information.Sometimes, we may need to extract all the 'words' from a long string, whether it is for keyword analysis, making tag clouds, or simply for reorganizing content display.At this time, the AnQiCMS template system provides a very practical tool - the `fields` filter, which can help us easily achieve this goal.

2025-11-09

How does the `wordcount` filter affect the performance overhead for long text? Will it affect the page loading speed?

In the daily operation of AnQi CMS, we all pay close attention to the performance of the website and the page loading speed, especially when dealing with a large amount of content.Regarding whether the `wordcount` filter will bring significant performance overhead and its impact on page loading speed is a common question.Today, let's delve deeply into this topic. ### Understanding the `wordcount` filter and its working principle First, let's clarify the role of the `wordcount` filter.

2025-11-09

What is the result returned by the `wordcount` filter for an empty string or a string that only contains spaces?

The template engine of AnQiCMS (AnQiCMS) provides a series of practical filters to help us flexibly handle data on the front-end page.Among them, the `wordcount` filter is a tool used to count the number of words in a string, which is often used in content operation to ensure that articles meet specific word count requirements or for content analysis.When discussing the `wordcount` filter, a common question is: what kind of result will it return when it encounters an empty string or a string that only contains spaces?

2025-11-09

How to use `wordcount` to create dynamic styles based on content length in AnQiCMS template design?

In website content operation, we often encounter a challenge: how to keep the website interface beautiful and readable when displaying content of different lengths?A brief news report and an in-depth industry analysis, they should be distinguished in layout and style to provide a better user experience.AnQiCMS (AnQiCMS) fully understands this need and provides powerful and flexible tools in template design to solve this problem.Today, let's discuss how to use AnQiCMS's `wordcount` filter to create dynamic styles based on content length

2025-11-09

The `wordcount` filter can be nested with other logical judgments (such as `for` loops)?

AnQiCMS provides a flexible and powerful template engine, allowing us to build website content with ease.In daily content display and data processing, there are often scenarios where you need to count the length of text, such as displaying the number of words in the abstract of an article list, or limiting the length of user comments.At this time, the `wordcount` filter comes into play.Many friends may be curious, whether the `wordcount` filter in the AnQiCMS template, in addition to being applied directly to variables, can also be used with other logical judgment tags, especially

2025-11-09

How to use `wordcount` as a preliminary measure of content quality before publishing an article?

In content operation, publishing high-quality articles is the core to attract users and improve search engine rankings.AnQiCMS (AnQiCMS) provides rich features to help us manage and optimize content.Before publishing the article, using some preliminary indicators for inspection can effectively improve the quality of the content.Among them, word count (`wordcount`) is a simple yet practical preliminary measure.Why Word Count is So Important for Content Quality?The word count is not just a number; it plays a multiple role in content quality assessment: 1.

2025-11-09