How does the `stringformat` filter customize the formatted output of any variable like Golang's `fmt.Sprintf()`?

Calendar 👁️ 79

In content operation, the way content is presented often determines the first impression and reading experience of users.Sometimes, simple variable output cannot meet our fine needs for data formatting display, such as hoping that numbers retain fixed decimal places or that specific text is added before output.An enterprise CMS provides powerful content rendering capabilities for template developers and content operators, among whichstringformatThe filter is the key tool for achieving fine-grained output. It is like in the Go language,fmt.Sprintf()A function that can format the output of any variable to a custom format, greatly enhancing the flexibility of the template.

Core Function and Purpose

stringformatThe core of the filter lies in its "formatting" ability. It comes into play when the variables in the template (whether they are numbers, strings, boolean values, or even complex data structures) need to be displayed in a specific layout or content.For example, you may need to always display the product price with two decimal places, or add a fixed prefix and pad the order number, or want to view the detailed type or structure of a variable in debug mode.stringformatIt is born for these scenarios, it allows us to control the final display form of variables through a formatted string.

Basic syntax

UsestringformatThe filter is very intuitive, its basic form is like this:

{{ 变量 | stringformat:"格式定义" }}

Here, 变量This is any template variable you wish to format格式定义It is a placeholder string that tellsstringformathow to process and output变量the value. This格式定义The syntax of strings in Go language isfmt.Sprintf()very similar, mastering it will unlock powerful formatting capabilities.

Common formatting placeholders

格式定义Strings contain various placeholders that provide different formatting options for different types of data. The following are some of the most commonly used placeholders and their purposes:

  • Numeric type placeholders:

    • %d: Formatted as a decimal integer.
    • %fFormatted as a floating-point number (decimal).
    • %e/%EFormatted as a floating-point number in scientific notation.
    • %bFormatted as a binary number.
    • %x/%XFormatted as a hexadecimal number.
    • %oFormatted as an octal number.
  • Placeholder for a string type.

    • %sFormatted as a basic string.
    • %qFormatted as a quoted string, with special characters escaped.
  • General type information placeholder:

    • %v: The default format representation of a variable.
    • %+v: When a variable is a struct, output its field names and field values.
    • %#v: When the variable is a struct, output its Go language source code representation.
    • %T: Output the Go language type of the variable.
    • %t: Format boolean values (true or false).
  • Width and precision control:You can also add numbers in placeholders to control the width and precision of the output.

    • %.2f: Format floating-point number, retaining two decimal places.
    • %5d: Format integer, total width of 5, fill with spaces on the left if insufficient.
    • %-10s: Format a string, total width is 10, left-aligned, and the insufficient part is filled with spaces on the right.
    • %05d: Format an integer, total width is 5, and the insufficient part is filled with zeros on the left.

Case Study

In order to understand betterstringformatThe practicality, let's look at some specific application scenarios:

1. Precisely control the decimal places of floating-point numbers

Suppose you have a price variablepricewith a value of199.998You want it to always display as two decimal places.

{% set price = 199.998 %}
<p>商品价格:{{ price|stringformat:"%.2f" }} 元</p>
{# 输出:商品价格:199.99 元 #}

2. Add a prefix to numbers and zero-fill them

If your order numberorderIdis an integer, you want it to be displayed in the form ofORD-00123format.

{% set orderId = 123 %}
<p>订单编号:{{ orderId|stringformat:"ORD-%05d" }}</p>
{# 输出:订单编号:ORD-00123 #}

Here%05dRepresents formatting an integer to a total width of 5 digits, padding with zeros on the left if necessary.

3. Format the output string.

You may need to add a specific display text for the website name, or output it in the form of a Go language string literal.

{% set siteName = "安企CMS" %}
<p>欢迎来到:{{ siteName|stringformat:"%s 官方网站" }}</p>
{# 输出:欢迎来到:安企CMS 官方网站 #}

<p>编程语言:{{ "Go语言"|stringformat:"%q" }}</p>
{# 输出:编程语言:"Go语言" #}

4. Check variable type or debug output

It is very useful to understand the actual type or internal structure of variables when developing or debugging templates.“`twig {% set myVar = “Hello AnQiCMS” %} {% set myNum = 123 %} {% set myData = {name:“AnQi”, version:“3.0”} %} {# 假设这是一个Map或结构体 #}

The type of myVar: {{ myVar|stringformat:%T }}

{# Output: The type of myVar: string #}

The details of myNum: {{ myNum|stringformat:%v }}

{# Output: myNum's details: 123 #}

myData's Go language structure: {{ myData|stringformat:%#v }}

{# Output similar: myData's Go language structure: map[string]interface

Related articles

How `split` and `make_list` filters split a string into an array by a specified delimiter or character?

In Anqi CMS template development, flexibly handling string data is an indispensable skill for building dynamic pages.Sometimes, we need to split a long string into a data list using a specified character or string as a delimiter (which is what we commonly call an array);At other times, we may need to process each character of the string independently.AnQi CMS provides two very practical filters: `split` and `make_list`, which can help us easily meet these needs.###

2025-11-08

How to slice a string or array elements within a specified range using the `slice` filter?

The AnQiCMS template engine provides rich filters, giving you great flexibility in displaying content.Among them, the `slice` filter is a very practical tool that can help you accurately extract elements within a specified range of strings or arrays, whether you want to display an article summary, limit the number of images, or handle other data segments, it can be very useful.### The working principle of the `slice` filter The syntax of the `slice` filter is concise and clear: `{{ obj|slice:"from:to" }}`

2025-11-08

How to search and replace specific keywords in the `replace` filter of the Anqi CMS template?

In the daily content management and template design of AnQi CMS, we often encounter scenarios where we need to search and replace specific content in strings.Whether it is to unify brand names, filter sensitive words, or adjust the display format of some text, manually modifying a large amount of content is undoubtedly cumbersome and inefficient.Fortunately, AnQi CMS provides a very practical template filter——`replace`, which can help us easily implement these string operations.### `replace` filter

2025-11-08

How does the `repeat` filter output a string repeated a specified number of times?

During the process of website content creation, there are times when we have the need to output a specific string multiple times, such as for visual separation, placeholder content, and quick generation of list items.In the AnQiCMS template system, the `repeat` filter provides a very practical function that can help us complete this task efficiently.This filter, as the name implies, repeats a string according to the number we specify, thus saving the trouble of manual copying and pasting, greatly enhancing the efficiency and flexibility of template writing.###

2025-11-08

How to get the thumbnail version of the image according to the image address using the `thumb` filter in the Anqi CMS template?

In website content management, the effective use of images is crucial for improving user experience and page loading speed.AnQiCMS deeply understands this, providing powerful image processing functions, among which the `thumb` filter is a tool that helps us easily obtain the thumbnail version of images.Why thumbnails are so important?Imagine if all the images on your website loaded in their original high-definition large size, how heavy the page would become!

2025-11-08

How do the `trim`, `trimLeft`, and `trimRight` filters remove spaces or specific characters from the beginning or end of a string?

In website operation and content management, we often encounter the need for string processing, especially in data entry, content display, or API interaction.For example, the user may have mistakenly entered multiple spaces before and after the text box, or some data may have been sourced with unnecessary specific characters.These seemingly minor issues may affect the layout and aesthetics of the content, even causing functional abnormalities.The AnQi CMS template engine provides a series of powerful filters to help us easily deal with these string cleaning tasks.Today, let's get to know the three very practical filters: `trim`

2025-11-08

How to handle truncation and add an ellipsis when truncating text with `truncatechars` and `truncatewords` filters, including HTML content?

In the increasingly fragmented information consumption era, the way websites present content directly affects user experience.Whether it is the abstract of an article list, the preview of product introduction, or various information stream cards, we need to convey the core information within a limited space while maintaining the page's neatness and uniformity of layout.This introduces the need for text truncation. AnQiCMS, as a fully functional content management system, understands this well and provides us with a powerful text truncation filter, especially its intelligent processing capabilities for HTML content, making content operations more relaxed.

2025-11-08

How to safely truncate text with HTML tags using `truncatechars_html` and `truncatewords_html` filters to prevent structure damage?

In website content operation, we often need to display the summary or part of the content in different scenarios, such as on the list page, search results, or related recommendations.This is when you need to truncate the content.If the content is plain text, a simple character or word cutter can handle the task well.However, when the content is rich in HTML tags, the problem becomes complex: directly cutting may cause the HTML tags to be truncated, thereby destroying the page structure, causing display errors, and even affecting the user experience.

2025-11-08