How to use filters in a template to format displayed numbers and strings (such as decimal places, case conversion)?

Calendar 👁️ 71

In the presentation of website content, the aesthetics and readability of the data are as important as the quality of the content itself.AnQiCMS (AnQiCMS) provides powerful filter (Filters) functions at the template level, allowing us to easily format numbers and strings displayed on the page, thereby enhancing user experience and the professionalism of page information.

Filter: The 'process' of data processing

We can imagine the filter as a series of processes for handling data.Raw data is like unprocessed raw materials, through the processing of filters, it can become the shape, size, or color we need.In Anqi CMS templates, using filters is very intuitive, usually using{{ 变量名|过滤器名称:参数 }}This format. Among them,变量名Is the data you need to process,|The symbol tells the template engine to apply a filter next,过滤器名称Is the specific operation, and参数This is a further setting for the operation (not all filters require parameters).

Precise control of number display: decimal places and arithmetic operations

When displaying prices, percentages, or other numerical values, we often need to control the number of decimal places or perform simple mathematical calculations.The filter provided by Anqi CMS offers a flexible solution.

Firstly, for the control of floating-point precision,floatformatThe filter is a very practical tool. It allows us to specify how many decimal places to retain for floating-point numbers. For example, if you have a product priceitem.PriceIs99.998And you want to display only two decimal places like this:{{ item.Price|floatformat:2 }}Then the content will be displayed on the page like this99.99. If the parameter is omitted, it will default to one decimal place and intelligently handle trailing zeros (for example99.00It will be displayed as99)

Sometimes, we need more refined formatting, even adding text to numbers. At this point,stringformatfilters come into play, which are similar to programming languages.SprintfFunction. For example, want to display the inventory quantity as “Inventory: 120 pieces”, anditem.Stockit is a number:“{{ item.Stock|stringformat:"库存: %d 件" }}Ifitem.Stockhas a value of120Then the page will display “Inventory: 120 pieces”.

Furthermore,integerandfloatThe filter can help us convert data types. When the data you get from some sources may be in string format (such as"123.45"But when you need to perform numerical operations on them:{{ "123.45"|float|integer }}This will first convert the string"123.45"Convert to a floating point number123.45And then convert to an integer123.

If you need to perform simple addition operations,addThe filter is very convenient, it can intelligently handle the addition of numbers and strings:{{ value1|add:value2 }}For example,{{ 5|add:2 }}Will be displayed7while{{ "安企"|add:"CMS" }}it will display:安企CMS.

Optimize string presentation: case conversion and content truncation

The formatting of strings is equally important, as it directly affects the professionalism and readability of the content. Anqi CMS provides a series of filters to process text.

In terms of case conversion, there are several commonly used filters:

  • upper: Converts all alphabetic characters in a string to uppercase.{{ item.Title|upper }}Ifitem.TitleIs "anqi cms", it will display "ANQI CMS".
  • lower: Convert all letters in the string to lowercase.{{ item.Title|lower }}Ifitem.TitleIt is "AnQi CMS", it will display "anqi cms".
  • capfirst: Convert the first letter of the string to uppercase and keep the rest unchanged.{{ "hello world"|capfirst }}It will display “Hello world”.
  • titleIt will capitalize the first letter of each word in the string.{{ "hello world"|title }}It will display “Hello World”.

Content truncation is a common requirement in website operations, such as article summaries, descriptions, etc.

  • truncatechars: Truncate the string based on the number of characters and add at the end....{{ item.Description|truncatechars:50 }}Willitem.DescriptionTruncate to a maximum of 50 characters (including...)
  • truncatewordsTruncate the string based on the number of words and add at the end....{{ item.Description|truncatewords:10 }}It will be truncated to a maximum of 10 words.

It is worth noting that if the content you want to truncate contains HTML tags, use it directly.truncatecharsortruncatewordsIt may destroy the HTML structure. Anqi CMS providestruncatechars_htmlandtruncatewords_html:{{ item.Content|truncatewords_html:30|safe }}This filter intelligently processes HTML tags, ensuring that the HTML structure remains intact after truncation. UsesafeThe filter is used to tell the template engine that the output HTML content is safe and does not need to be automatically escaped.

Practical Tips: Filter Chains and More Exploration

The filter design of AnQi CMS is very flexible, you can link multiple filters together for use, and they will be executed in order from left to right. For example: {{ item.Title|lower|capfirst|truncatechars:20 }}This will first convert the title to lowercase, then capitalize the first letter, and finally truncate to 20 characters.

The AnQi CMS template engine is built-in with a rich variety of filters, which are only a part of what is introduced here. When you encounter specific formatting needs, it is recommended to consult the official documentation of AnQi CMS regarding the 'More Filters' section (usually in thetag-filters.mdIn it, a detailed list of all available filters and their usage is listed, including string replacement, deletion, array operations, URL processing, and more.By trying and combining different filters, you can almost meet all the display needs of page data.

Adopt these filters flexibly to present your website content in the most elegant and user expectations, greatly enhancing the professionalism and user experience of your website.


Frequently Asked Questions (FAQ)

  1. Why is the filter not working or giving an error?This is usually caused by several situations. First, check that the variable name and filter name are spelled correctly, and ensure|The symbol is used correctly. Secondly, confirm that the data type you pass to the filter meets its requirements (for example,dateThe filter needstime.Timetype, andfloatformatNeed a number or a string that can be converted to a number). Sometimes, if a filter requires parameters and you forget to provide them, an error may occur.Finally, for variables containing HTML content, if not used|safeFilter, the template engine may escape it, making it look different from what you expect to be formatted.

  2. Can I apply multiple filters to the same data?Of course you can! Anqi CMS template filters support chaining. This means you can use multiple filters with|Symbols are connected together, and they act on the data in the order you write them, from left to right. For example,{{ item.Title|lower|capfirst|truncatechars:20 }}The title will be converted to lowercase, then the first letter will be capitalized, and finally truncated to 20 characters.

  3. How do I choose the correct filter to process my data?The choice of an appropriate filter mainly depends on the effect you want to achieve and the type of original data.First, clarify your goal: do you want to control the precision of numbers? Convert case?Should the text be truncated? Or should some other processing be performed? Then, refer to the AnQi CMS filter documentation based on the data type (numbers, strings, HTML content, timestamps, etc.).The document usually provides detailed descriptions and examples of each filter, helping you quickly find and understand how to use it.Try and practice more are the ways to master these skills.

Related articles

How to correctly display HTML rich text content in article content using the `safe` filter?

In website content operation, rich text content plays a vital role.It allows us to enrich the expression of the article with various formats such as images, links, bold, italic, and more, enhancing the reading experience.AnQiCMS (AnQiCMS) provides a powerful backend editor, making it easy for us to create various wonderful content.However, when this rich text content is finally displayed on a website page, sometimes you may find that the original beautiful formatting and links have become raw HTML code strings. Why is that?

2025-11-09

How to display both subcategories and the list of articles under the category on a category page?

When operating the AnQiCMS website, we often encounter such a need: on a category page, we not only want to display the list of articles under the category but also clearly list all its subcategories to facilitate users in making more detailed navigation.The Anqi CMS, with its flexible template engine and rich built-in tags, can fully help us easily achieve this goal. ### Understanding AnQi CMS Category Page and Template Mechanism In AnQi CMS, each category (whether it is an article category or a product category) can be associated with an independent template file. Generally speaking

2025-11-09

How to manage and display category Banner images and thumbnails?

In website operation, the category page is an important link in guiding users to browse and deepen the brand impression.To configure a unique banner image and thumbnail for the category page, it can not only enhance the visual appeal of the website, but also allow users to intuitively understand the category content, effectively optimizing the user experience.AnQi CMS provides flexible and easy-to-operate functions in this regard, helping us manage and display these visual elements efficiently.

2025-11-09

How to dynamically filter and display a list of articles through URL parameters or search keywords?

Today, with the increasing refinement of content management, how to make your website content smarter and more considerate in serving visitors is the key to improving user experience and website value.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides powerful functions to help us achieve this, especially in terms of dynamic filtering and displaying article lists. The combination of template tags with URL parameters allows for easy construction of highly customizable content presentation methods.This article will give a detailed introduction on how to use URL parameters and search keywords

2025-11-09

How to add special styles to specific items when displaying in a list, based on the count in a for loop?

In website content display, we often need to highlight specific items in the list visually, whether it is to attract the attention of users or to enhance the hierarchy of the content.For example, you may want to add a "pin" mark to the latest few articles published, or make the odd and even rows of the list display different background colors to enhance readability.AnQiCMS (AnQiCMS) flexible template engine, which provides powerful support for these refined controls.AnQiCMS's template system borrows the syntax of the Django template engine

2025-11-09

How to implement the automatic display of content collected on the website front end?

How to automatically display the collected content on the website front-end is a concern for many content operators.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides a complete solution from content entry to front-end display.It goes through a powerful content model, flexible template tags, and a friendly SEO mechanism, making this process simple and efficient.Next, we will explore how to use the various functions of AnQiCMS to automatically and beautifully display the valuable content you collect on the website's front-end.###

2025-11-09

How to prevent HTML tags from being automatically escaped when content is displayed?

When using Anqi CMS to manage website content, you may encounter a seemingly small but annoying problem: the formatted HTML code entered in the background editor is displayed as plain text on the front page, even presented directly in the form of angle brackets, losing the original style and layout.This not only affects the appearance of the page, but also discounts the carefully arranged content.Why is that, and how should we solve it?###

2025-11-09

How can you reference and overwrite the base master template (extends) in a template to unify the display style?

In the world of AnQiCMS, building a website with a unified appearance, easy to manage, and efficient to update is a common pursuit of each content operator and developer.Imagine if each page of the website needed to be designed individually for the header, footer, and sidebar, then the amount of work required to modify the logo, navigation menu, or copyright information would be enormous.Luckyly, AnQiCMS cleverly utilizes the template inheritance mechanism, allowing us to easily achieve a unified display style while maintaining flexible content updates

2025-11-09