Which formatting placeholders does the `stringformat` filter support?

Calendar 👁️ 63

In AnQiCMS template development, in order to better display and control the presentation of data on the page, we often need to format variables. Among them,stringformatA filter is a very practical tool that allows us to convert numbers, strings, or other types of values into a specific string format according to predefined rules. The strength of this filter lies in its adoption of the Go language infmt.Sprintf()The syntax of placeholder function makes the control of output format flexible and accurate.

stringformatThe filter supports a variety of placeholders to meet the formatting needs of different data types. Understanding these common placeholders can help us present website content more efficiently and beautifully.

Generic placeholder

These placeholders are applicable to any type of data, they try to 'print' the variable in different ways:

  • %vThis is the most basic placeholder, which will output the variable in its default format. For example, an integer will be displayed in decimal, and a string will be output directly.
  • %+vWhen processing a structure (such as the document object, category object, etc. in AnQiCMS), use%+vIt will output its value and also include the field name, which is very useful for debugging as it can clearly show each attribute's name and its corresponding value.
  • %#vThis placeholder will output the Go representation of the value, including the type information and field name.This is very helpful for understanding the underlying structure and type of variables, especially when troubleshooting template rendering issues.
  • %TIf you just want to know what the type of a variable in Go is,%Tit can be used. It will directly output the type name of the variable, for example,int/string/structetc.

numeric placeholder

for numbers,stringformatProvide multiple ways to control their display:

  • %dUsed to output decimal integers. No matter your number is:intOruintIt will be displayed in standard decimal form.
  • %f: Used to output floating-point numbers (such as prices, percentages, etc.). You can control the number of decimal places by adding a precision modifier, for example%.2fmeans retaining two decimal places.
  • %eor%E: If you need to represent floating-point numbers in scientific notation, you can use these placeholders.%eUse lowercasee,%EUse uppercaseE.
  • %b: Convert the number to binary representation.
  • %c:Interpret an integer value as a Unicode code point and output the corresponding character.
  • %x:Convert a number to its hexadecimal representation.

String placeholder

When processing text content, these placeholders can provide additional control:

  • %sThe most commonly used string placeholder, directly outputs the string content.
  • %qOutput a double-quoted string literal. If the string itself contains special characters,%qIt will be properly escaped to ensure the output conforms to the string literal specification of the Go language.

Control of width and precision

In addition to the placeholder itself, we can also control the output width and precision by adding numbers before the placeholder:

  • Width control: Add a number between the placeholder and the percentage sign, for example%5dThis indicates that the output number must occupy at least 5 characters in width. If the number itself is less than 5 digits, spaces will be filled on the left; if it exceeds 5 digits, it will be displayed normally.
  • Precision control: For floating-point numbers, you can use a placeholder before it.to control the number of decimal places after the decimal point, for example%.2fit will format the floating-point number to retain two decimal places.
  • width and precision combinedBoth can be used together, such as%5.2fIndicates that the total width is at least 5 digits, with two decimal places retained.
  • Left-alignedBy default, when the width is insufficient, it is right-aligned with spaces filled on the left. If you want to be left-aligned, you can add before the width number-For example%-5sIt will make the string left-aligned with spaces filled on the right.

Actual application example

Assuming we have a product objectproductwhich includesPrice(a floating point number),Stock(Integer) andName(a string) and other properties. We hope to display the following information in the template:

商品名称:{{ product.Name|stringformat:"%s" }}
商品价格:{{ product.Price|stringformat:"¥%.2f" }}
剩余库存:{{ product.Stock|stringformat:"%d 件" }}
商品详情:{{ product.Description|stringformat:"商品描述: \"%q\"" }}
产品类型(调试用):{{ product|stringformat:"%T" }}
完整产品信息(调试用):{{ product|stringformat:"%+v" }}

As can be seen from the above examples,stringformatThe filter can provide powerful formatting capabilities in practical development.No matter whether it is to beautify the data visible to the user or to quickly view the detailed information of variables during development debugging, it is an indispensable tool.


Frequently Asked Questions (FAQ)

  1. stringformatFilters andstampToDateWhat are the differences between filters? stringformatThe filter is mainly used to output various data types (such as numbers, strings, booleans, structs, etc.) in a specific string pattern, with the placeholder syntax based on the Go language'sfmt.SprintfHoweverstampToDateThe filter is specifically used to handle timestamps, converting Unix timestamps to readable date and time formats, and supporting the standard date format strings in Go language as parameters. In short, ...stringformatIs a general-purpose formatting tool,stampToDateIs specialized in timestamp conversion.

  2. What will happen if the formatted value type does not match the placeholder completely? stringformatThe filter at the bottom attempts to perform type conversion to match the placeholder, but its behavior may vary due to Go languagefmt.SprintfThe specific implementation varies. Usually, Go will try to provide a reasonable default output (for example, wrapping strings in%dFormatting may result in 0 or an error message, using numbers instead%sFormatted, the string representation of a number will be output), but in this case, the output result may not be as expected, and even lead to template rendering errors. Therefore, when usingstringformatAt the same time, it is recommended to ensure that the placeholder selected is as compatible as possible with the actual data type of the variable.

  3. In addition to what is mentioned in the article, what are some aboutstringformatadvanced usage or techniques? stringformatas a Go languagefmt.SprintfThe encapsulation, its advanced usage is basically consistent with the formatting rules of the Go language. For example, you can use%the symbol to define the padding character (%05dThis represents padding with zeros to 5 digits) or controlling the precision of the floating-point number output(%.nfof whichnfor the number of decimal places). Moreover, combinestringformatWith other logic judgments or loop tags of the AnQiCMS template, you can build very complex dynamic content display logic. It is recommended to consult the official Go language documentation aboutfmt.SprintfThe detailed description to explore more advanced techniques.

Related articles

How to format numbers, strings, and any other values to output as strings in a specific format (`stringformat`)?

In the display of website content, we often need to present different types of data (such as numbers, strings, and even more complex structures) in a unified and precise manner on the page.The template engine of AnQiCMS provides powerful tools, one of which is a very practical feature called `stringformat` filter, which can help us format any value into a string of a specific format.When we retrieve data from the backend, whether it is the number of views of an article, the price of a product, or user-defined parameters, they may be represented by numbers

2025-11-08

What will the `get_digit` filter return if the position it accesses does not exist?

In AnQi CMS template development, flexibly using various filters (filters) can greatly enhance the efficiency and accuracy of content display.`get_digit` filter is one of the practical tools used to process numeric data.It allows us to extract a specific digit from a number accurately.However, a common issue during usage is: What will the `get_digit` filter return if the position being accessed exceeds the length of the number itself?### `get_digit`

2025-11-08

How to get the Nth digit from the end of a number using the `get_digit` filter?

During the template creation process of Anqi CMS, we often need to handle data flexibly so that the most user-friendly information can be displayed on the front-end page.Numbers are a common form of data, and sometimes we may need to extract a specific number from a longer number.At this point, the `get_digit` filter can be put to use, which can help us easily obtain the Nth digit from the end of a number.### The core function and purpose of the `get_digit` filter The `get_digit` filter is as its name suggests

2025-11-08

How can you determine in a template if a number can be evenly divided by another number?

In web content display, we often encounter situations where we need to adjust the layout or style based on the divisibility of numbers, such as setting different background colors for odd and even rows of a table, or starting a new row for grouping display every fixed number of contents.In AnQi CMS template system, implementing such logical judgment is quite direct and efficient.The AnQi CMS template engine is designed to be very flexible and easy to use, it adopts a syntax structure similar to Django templates, allowing us to use simple variable references (`{{ variable_name }}`) and logical control tags (`{% if ...`)].

2025-11-08

How to display product prices in AnQiCMS templates and control decimal places?

In website operation, the display of product prices is a crucial link, not only to ensure the accuracy of information, but also to ensure that the presentation method conforms to the reading habits and brand image of users.AnQiCMS with its flexible template system, provides users with powerful customization capabilities, allowing you to easily control the display of product prices, including decimal places.### How to get product price: Where does it come from? In the AnQiCMS template, the product price is usually stored and called as a field of the document (Article or Product)

2025-11-08

How can I perform numerical calculations based on a user-defined parameter (string)?

During website operation, we often encounter scenarios where we need to perform calculations on custom data, such as dynamically calculating prices based on product parameters, displaying rating statistics, or performing other numerical processing based on user input or content attributes.AnQi CMS provides us with the ability to meet these requirements with its flexible content model and powerful template engine.This article will introduce in detail how to perform numerical calculations based on custom string parameters in Anqi CMS.### First Step: Preparation - Define Your Custom Parameters First

2025-11-08

How can I convert a string price from a custom field into a number that can be used in the order total in the template?

In website operation, we often encounter the need to handle numerical data such as product prices or service charges.This data is sometimes stored in custom fields, but for various reasons, they may be saved in the form of strings (text), such as "199.50 yuan" or "150".When we need to perform a total calculation on these prices in a template (such as the order total), directly performing a 'sum' operation on the string will yield unexpected results (such as '199.5015.00' instead of '214.50').At this point, it is necessary to convert these string prices into actual numbers

2025-11-08

How to dynamically adjust the decimal precision of displayed numbers in a template?

In website content operation, the precise display of numbers is often crucial, whether it is product prices, statistical data, or technical indicators, the accuracy of decimal point display directly affects the accuracy of information and the understanding of users.AnQiCMS provides a flexible template engine that allows us to easily adjust the decimal precision of numbers in frontend templates, thus satisfying various complex display requirements.The AnQiCMS template system is developed based on Go language, with a syntax style similar to Django, it offers powerful Filter (Filter) functions

2025-11-08