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

Calendar 👁️ 56

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. AnQiCMS (AnQiCMS) provides powerful tools for this, one of which is a very practical feature that isstringformatA filter that helps us format any value as a string in 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 exist in the form of numbers, boolean values, or raw strings.But the front-end page often has specific requirements for displaying these data, such as prices need to be kept with two decimal places, percentages do not need decimal places, or some data need to be displayed with prefixes and suffixes. At this time,stringformatThe filter is particularly important, as it is like a professional 'data整形师', able to modify various data according to our wishes, shaping it into the most suitable string for display.

For users familiar with AnQiCMS in Go language,stringformatthe working style will be very familiar, because it is consistent with the built-infmt.Sprintf()The function is very similar, controlled by a set of format verbs to control the output.This means you can take advantage of the powerful formatting capabilities of the Go language to implement complex data display logic in the AnQiCMS template.

How to usestringformatFilter?

stringformatbasic usage of the filter is very intuitive:

{{ 要格式化的值|stringformat:"格式定义" }}

Here:

  • 要格式化的值is any variable or literal you want to format, it can be a number, string, boolean, or even complex data structures.
  • "格式定义"Is a string that contains the instructions on how you want to format the values, these instructions are the formatting verbs mentioned earlier.

Here are some commonly used formatting verbs and their application scenarios:

  1. String (%s)This is the most basic formatting verb, used to convert any value to a string.It is very useful when you need to convert non-string values to strings, or to embed other strings within a string.

    {% set articleTitle = "安企CMS入门指南" %}
    <p>{{ articleTitle|stringformat:"文章标题:%s" }}</p>
    {# 输出: 文章标题:安企CMS入门指南 #}
    
  2. Integer (%d): Designed for integer values. If you want to ensure that numbers are displayed in pure integer form or to add specific text before or after the number, you can use it.

    {% set viewCount = 12345 %}
    <p>浏览量:{{ viewCount|stringformat:"%d 次" }}</p>
    {# 输出: 浏览量:12345 次 #}
    
    {% set productId = 888 %}
    <p>产品编号:{{ productId|stringformat:"P-%d" }}</p>
    {# 输出: 产品编号:P-888 #}
    
  3. Floating point number (%f,%.NF)Handling numbers with decimals.%fWill display floating-point numbers with the default precision, and%.NF(where N is a number) it is possible to accurately control the number of decimal places and round off. This is the most commonly used method in scenarios such as displaying prices, ratios, etc.

    {% set productPrice = 99.998 %}
    <p>价格:{{ productPrice|stringformat:"%.2f 元" }}</p>
    {# 输出: 价格:100.00 元 (进行四舍五入) #}
    
    {% set discountRate = 0.85 %}
    <p>折扣:{{ discountRate|stringformat:"%.0f%%" }}</p>
    {# 输出: 折扣:85% (注意这里需要先将0.85转换成85再格式化) #}
    

    Supplementary explanation: If you need to convert0.85Formatted as85%Multiply first:{{ (discountRate * 100)|stringformat:"%.0f%%" }}.

  4. Universal value (%v,%+v,%#v)These are very powerful formatting verbs, especially for debugging or displaying the original structure of variables.

    • %v: Prints the value in the default format.
    • %+v: When printing a struct, it will print the field names and their values.
    • %#v: Prints the value in Go language syntax representation, for structs, it will display the type and fields.
    • %TPrint the Go language type of the value.
    {# 假设有一个名为 article 的复杂对象 #}
    <p>文章对象详情:{{ article|stringformat:"%v" }}</p>
    <p>文章对象类型:{{ article|stringformat:"%T" }}</p>
    {# 这在调试时非常有用,可以直观地查看变量内容和类型 #}
    

Combined with the actual application of AnQiCMS template tags.

stringformatIts strength lies in the fact that it can be used with various data retrieval tags in AnQiCMS (such asarchiveDetail/system/contactCombine seamlessly

For example, get the website name from the system settings and format it for output:

{% system siteName with name="SiteName" %}
<title>{{ siteName|stringformat:"%s - 我们的网站" }}</title>
{# 假设siteName是"安企CMS",输出: <title>安企CMS - 我们的网站</title> #}

Or, format the number of views of the document more friendlily on the document detail page:

{% archiveDetail views with name="Views" %}
<p>本文已有 {{ views|stringformat:"%d 人阅读" }}</p>
{# 假设views是500,输出: <p>本文已有 500 人阅读</p> #}

By flexibly using these formatting verbs, we can display any data obtained from the AnQiCMS backend in the string format that best fits the user interface and business logic, greatly enhancing the professionalism and user experience of the website content.

Frequently Asked Questions (FAQ)

1.stringformatandstampToDateWhat is the difference? When should I use them? stringformatIt is a general string formatting tool that can handle various types of data such as numbers, strings, and more.stampToDateIs a label specifically used to format a 10-digit Unix timestamp into a datetime string. If you need to format a timestamp into a readable date format, you should usestampToDateIf you need to format strings for other types, or need to control the precision, prefix, and suffix of numbers, then usestringformat.

2. When I want to format floating-point numbers and control the number of decimal places, I should choosestringformatOrfloatformat? What are the differences between them?Both can be used to format floating-point numbers and control the number of decimal places.

  • stringformat:"%.2f"Strictly adheres to the Go language'sfmt.Sprintf()formatting rules, regardless of the number of decimal places in the original number, it will always output two decimal places (for example10Will become10.00,9.998Will become10.00)
  • floatformat:2(or specify other numbers) is also used for floating-point number formatting, it retains the specified number of decimal places, but there is a feature that if the last digit is 0, it may not be displayed (for example10.00It will be displayed as10,9.998becomes10.00)。In addition,floatformatIt also supports negative number of digits, used to truncate from the right. In summary, if you needStrict and alwaysDisplay decimal places to the specified number (even if it is zero),stringformatMore reliable; if you want toDisplay decimal places more "naturally" while maintaining accuracy(For example, omitting trailing zeros),floatformatMaybe this is more appropriate.

3.stringformatCan be used to truncate long strings? stringformatMainly used forFormatinstead ofTruncate. Although you can indirectly affect the output length with some complex formatting verbs (such as combining width limits), this is usually not its purpose.If you need to truncate a long string and add an ellipsis at the end (such as “…”), it is recommended to use the template provided in AnQiCMStruncatecharsortruncatewordsFilters, they are more professional and convenient for handling such needs.

Related articles

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

What happens when the `add` filter performs mixed addition and type conversion fails?

In the AnQi CMS template world, we often use various filters to process data, making the page display more flexible.Among them, the `add` filter is a very practical tool that allows us to add or concatenate two values.In most cases, its performance is very intuitive: when numbers are added to numbers, mathematical operations are performed;When two strings are added together, a simple text concatenation is performed.When a number is added to a string, it also cleverly converts the number to a string and concatenates it, for example, `{{ 5|add:"CMS" }}` results in `5CMS`

2025-11-08

Which formatting placeholders does the `stringformat` filter support?

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, the `stringformat` 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 placeholder syntax of the Go language `fmt.Sprintf()` function, making the control of output format flexible and accurate

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