What advanced formatting options does the AnQiCMS `stringformat` filter support (such as outputting percentages, scientific notation)?

Calendar 👁️ 70

In AnQiCMS template development, the flexibility of data display is often a key factor in determining user experience and the professionalism of content presentation. Among them,stringformatFilter is undoubtedly a powerful tool that allows us to finely format various data types, meeting from simple precision control of numbers to complex percentages, scientific notation, and other advanced requirements.

stringformatFilter: The data formatter in the template

stringformatThe filter is like a data formatter in the template, its core function is to mimic the built-in Go languagefmt.Sprintf()Function, which converts numbers, strings, and even more complex data types into strings according to a predefined format.This means that, regardless of whether your data is an integer, a floating-point number, or plain text, you can customize the final display style through it.

It includes the most basic application of controlling the display accuracy of floating-point numbers, for example, if you have a floating-point number3.141592653and you want it to display only two decimal places, you can use it like this:

{{ 3.141592653|stringformat:"%.2f" }} {# 输出:3.14 #}

here,%.2fTell the filter to format numbers as floating-point numbers and retain two decimal places. Similarly, it handles integers or embedded strings with ease:

{{ 99|stringformat:"数值:%d" }} {# 输出:数值:99 #}
{{ "AnQiCMS"|stringformat:"系统名称:%s" }} {# 输出:系统名称:AnQiCMS #}

These basic usages provide convenience for data display, butstringformatits true power lies in its support for advanced formatting options.

Advanced formatting options: Let the data 'speak'.

In many business scenarios, we need to present data in a more expressive way, such as percentages in financial statements, scientific notation in scientific research, or precise control of text alignment.stringformatThe filter provides various advanced options to help us achieve these goals.

Output percentage

Directly outputting a decimal as a percentage often does not conform to people's reading habits. For example,0.15Generally displayed as15%. With the help ofstringformat, we can easily achieve:

First, multiply the original decimal by 100, then use%.0f(a floating point number without decimal places) or%.2f(Format as a floating-point number with two decimal places and then manually concatenate the percentage sign.)

{% set discount = 0.15 %}
产品折扣:{{ (discount * 100)|stringformat:"%.0f" }}% {# 输出:产品折扣:15% #}

{% set completion_rate = 0.9876 %}
完成率:{{ (completion_rate * 100)|stringformat:"%.2f" }}% {# 输出:完成率:98.76% #}

After this process, the originally dull numbers are transformed into intuitive percentage forms, greatly enhancing the readability of the information.

Scientific notation

When dealing with very large or very small numbers, scientific notation is a standard and concise way of representation.stringformatBy%eand%EThese formatting verbs support scientific notation:

  • %eConvert numbers to scientific notation using lowercase letterseIndicates the exponent.
  • %EConvert numbers to scientific notation using uppercase lettersEIndicates the exponent.
{% set large_number = 123456789.12345 %}
宇宙距离:{{ large_number|stringformat:"%e" }} 米 {# 输出:宇宙距离:1.234568e+08 米 #}

{% set small_number = 0.00000012345 %}
粒子大小:{{ small_number|stringformat:"%E" }} 毫米 {# 输出:粒子大小:1.234500E-07 毫米 #}

In this way, even facing extreme values, we can maintain clear and professional presentation in the template.

Width and alignment

Sometimes you need to control the width and alignment of the output result to achieve a neat table or report layout.stringformatAllow you to specify the minimum width of the output field and decide whether to align left or right:

  • %[width]s: Right-align the string and fill it with spaces on the left until it reaches the specified width.
  • %-[width]sLeft-align a string and fill with spaces on the right until the specified width is reached.
  • %[width]dRight-align an integer and fill with spaces on the left.
{% set product_name = "高端服务器" %}
{% set price = 12345 %}
商品列表:
- 名称:{{ product_name|stringformat:"%-15s" }} 价格:{{ price|stringformat:"%8d" }} 元
{% set product_name_b = "入门主机" %}
{% set price_b = 899 %}
- 名称:{{ product_name_b|stringformat:"%-15s" }} 价格:{{ price_b|stringformat:"%8d" }} 元
{# 示例输出:
- 名称:高端服务器     价格:   12345 元
- 名称:入门主机       价格:     899 元
#}

This alignment is very useful when generating structured output (such as reports, receipts).

Other useful number formats

stringformatIt supports some other number formatting options, although not commonly used, they can be very practical in certain scenarios:

  • %b: Converts an integer to binary representation.
  • %x/%XConvert integer to hexadecimal representation (lowercase/uppercase).
  • %cConvert integer to corresponding Unicode character.
{% set decimal_value = 99 %}
二进制:{{ decimal_value|stringformat:"%b" }} {# 输出:二进制:1100011 #}
十六进制:{{ decimal_value|stringformat:"%x" }} {# 输出:十六进制:63 #}
字符:{{ decimal_value|stringformat:"%c" }} {# 输出:字符:c #}

These options provide flexible solutions for lower-level or specific data display requirements.

View data types and structures

When debugging or unsure of variable content,%v/%+v/%#vand%TThese formatting verbs can help us better understand the data:

  • %v: The default format for outputting values.
  • %+v: When the value is a struct, it will output the field names and values.
  • %#vOutput the Go language syntax representation of the value (i.e., the source code snippet).
  • %TOutput the Go language type of the value.
{% set my_variable = {"key": "value", "number": 123} %}
普通输出:{{ my_variable|stringformat:"%v" }}
带字段名:{{ my_variable|stringformat:"%+v" }}
Go语法:{{ my_variable|stringformat:"%#v" }}
类型:{{ my_variable|stringformat:"%T" }}
{# 实际输出会因变量的具体结构而异,但能提供丰富的调试信息 #}

Summary

stringformatThe filter brings powerful data formatting capabilities to the AnQiCMS template.From controlling decimal places to outputting percentages, scientific notation, and fine text alignment and type checking, it allows content managers and developers to present data in a highly customized and professional manner.Mastery of these advanced formatting options can greatly enhance the presentation of website content and provide a more accurate, user-friendly experience.

Related articles

How to get the first or last image address of an array (such as an image list) in AnQiCMS template?

In Anqi CMS template design, flexibly displaying and managing images is an indispensable part of building a high-quality website.When the content contains multiple images, such as group images on product detail pages or article illustrations, we often need to accurately extract one of the images, such as using the first image as a thumbnail or cover, or obtaining the last image for special display.This article will discuss in detail how to easily obtain the address of the first or last image in the image array of the AnQiCMS template.

2025-11-07

How does the AnQiCMS `count` filter calculate the total number of times a specific keyword appears in the article content?

## Deep Analysis: AnQiCMS `count` filter counts the number of keyword occurrences in article content In daily website operations, we often need to understand certain key information in the article content, such as how many times a specific keyword appears in the article.This is crucial for SEO optimization, content quality assessment, or internal audit.AnQiCMS as an efficient content management system provides rich template tags and filters, making this work simple and intuitive. Today

2025-11-07

How to efficiently check if a long string or array contains a certain keyword in the AnQiCMS template?

In the daily operation of AnQiCMS, we often need to quickly and accurately judge whether a specific keyword or phrase exists in the dynamic content of the website, such as the main body of articles, product descriptions, custom fields, and even tag lists and category names.This requirement is particularly common in content management, SEO optimization, or personalized display.How can you efficiently complete this task in the flexible and powerful template system of AnQiCMS?

2025-11-07

How to repeat a specific string (such as a separator) multiple times in the AnQiCMS template?

In web template design, we often encounter the need to repeatedly output a specific string or character pattern to achieve visual separation, emphasis, or layout effects.For example, you may want to display a line composed of multiple dashes between content blocks, or repeat asterisks to decorate an area.In the AnQiCMS template system, thanks to its syntax similar to the Django template engine, achieving such repeated output is very flexible and efficient.

2025-11-07

How to safely convert a user input numeric string to an integer or floating-point number for calculation in AnQiCMS template?

In daily website operations, we often encounter the need to display or calculate user input data on the webpage.Even when fields are explicitly set as numeric types in the background, when the data is fetched to the front-end template for rendering, they are often in the form of strings.This is not a problem when displaying simple content, but once it involves numerical calculations, such as calculating the total price, calculating percentages, etc., direct string operations can lead to unexpected results and even errors.

2025-11-07

AnQiCMS `trim` family filter can delete which custom characters besides spaces?

In AnQi CMS template design, we often need to process the displayed data to ensure that the content presented to the user is both beautiful and accurate.Among them, string processing is an indispensable part of content operation.AnQi CMS provides a series of flexible filters that help us easily complete these tasks, and the `trim` family of filters is one of the very practical ones. At first, we might think that the `trim` filter is mainly used to remove whitespace characters from the beginning and end of a string, such as extra spaces or newline characters.

2025-11-07

How to URL encode query parameters in AnQiCMS template to avoid conflicts with special characters?

When building dynamic links in the AnQiCMS template, we often need to pass variables as query parameters in the URL.For example, a search results page may need to pass the user's search term as a parameter;A category filter page may need to include the selected category ID or multiple filter conditions.However, these dynamic contents often contain special characters, such as spaces, `&`, and `?`Backticks, equals, slash, hash, etc., they have specific meanings in URLs.If these special characters are not processed, the browser or server may not be able to correctly parse the URL, resulting in a page error

2025-11-07

How to count word numbers with the `wordcount` filter of AnQiCMS when processing mixed Chinese-English text?

In Anqi CMS template design, the `wordcount` filter is a practical tool used to count the number of words in the text.For operation personnel and content creators, understanding the working principle, especially the statistical logic when dealing with mixed Chinese and English text, can help us accurately assess content length, optimize article structure, and better meet the needs of search engine optimization (SEO) and user reading experience.### `wordcount` filter basic usage The `wordcount` filter is very straightforward to use

2025-11-07