In the template development of AnQi CMS, we often need to display various data obtained from the backend in a specific and beautiful format to the website visitors.Whether it is the price of goods, the reading volume of articles, or the balance of user points, the original way of presenting data may not always be ideal.stringformatThe filter then becomes a very practical tool.
stringformatThe filter helps us format output of numbers, variables, and even more complex structures according to the predefined string pattern.In simple terms, it's like a professional typesetter who can 'beautify' raw data into a unified and standardized text format based on the 'typesetting instructions' you provide.Understand and effectively use this filter to greatly enhance the user experience and professionalism of the website content.
stringformatThe core mechanism of the filter
In the template system of Anqi CMS,stringformatThe underlying implementation of the filter and Go language'sfmt.Sprintf()functions are closely related. This means that if you are familiar with Go language's formatting string syntax, then usingstringformatThe filter is easy to handle. Even if you are not familiar with it, you can quickly master its usage through some common format definitions (also known as 'format verbs').
Its basic syntax is very intuitive:
{{ 变量 | stringformat:"格式定义" }}
Here are the变量[en]It is the data you want to format, and格式定义is a string containing special symbols, which tell the filter how to handle and display your variables.
Common application scenarios
stringformatThe filter is widely used in the display of website content, the following are some of the most common examples:
1. Precise control of number display
Numbers are one of the most frequently needed to be formatted data types, especially when it comes to currencies, percentages, or specific precision requirements.
Formatting floating-point numbers:When we need to display product prices, discount percentages, or numbers with fixed decimal places,
stringformatit comes in handy. For example,%.2fThe value indicates formatting a floating-point number to two decimal places.{% set productPrice = 99.998 %} {% set discountRate = 0.15 %} <p>商品价格:{{ productPrice | stringformat:"%.2f" }} 元</p> {# 输出:商品价格:99.99 元 #} <p>优惠百分比:{{ discountRate * 100 | stringformat:"%.1f%%" }}</p> {# 输出:优惠百分比:15.0% #}Here are the
%frepresents a floating-point number,.2specifies two decimal places,%%It means to output a literal percentage sign.Formatting integers:Ensure the integer data does not have a decimal point, or is displayed with a specific width.
%dIs a common verb used for formatting integers.{% set articleViews = 12345 %} {% set productStock = 88 %} <p>文章阅读量:{{ articleViews | stringformat:"%d" }}</p> {# 输出:文章阅读量:12345 #} <p>库存数量:{{ productStock | stringformat:"%03d" }}</p> {# 输出:库存数量:088 (使用0填充到3位宽度) #}%03dof0indicating zero-padding.3indicating the total width is 3 characters.
2. Constructing Dynamic Strings and Composing Information
stringformatIt can also effectively help us combine different types of data to generate more readable description text.%sUsed for general string replacement,%vis the default representation of a value.
Combine text information:Embed multiple variables into a sentence to form a coherent sentence.
{% set productName = "智能手机" %} {% set productModel = "AQ-Pro" %} {% set releaseYear = 2023 %} <p>最新发布:{{ productName | stringformat:"%s (%s)" : productModel }}</p> {# 这里的: productModel是第二个参数 #} {# 或者更直观地使用多个变量占位 #} <p>最新发布:{{ "最新发布的 %s 型号为 %s,发布于 %d 年。" | stringformat:productName, productModel, releaseYear }}</p> {# 输出:最新发布:智能手机 (AQ-Pro) 和 最新发布的 智能手机 型号为 AQ-Pro,发布于 2023 年。#}When
stringformatWhen combining multiple values, the format definition string can be followed directly by the variables to be filled in, separated by commas.Display complex objects or debug information:When debugging templates, it is sometimes necessary to view the internal structure of a complex object (such as a structure, array):
%v/%#vand%Tit can be very useful.{% set user = {ID: 101, Name: "张三", IsAdmin: true} %} <p>用户对象详情 (Go默认表示):{{ user | stringformat:"%v" }}</p> {# 输出:用户对象详情 ({101 张三 true}) #} <p>用户对象详情 (Go代码表示):{{ user | stringformat:"%#v" }}</p> {# 输出:用户对象详情 (main.User{ID:101, Name:"张三", IsAdmin:true}) #} <p>用户变量类型:{{ user | stringformat:"%T" }}</p> {# 输出:用户变量类型:map[string]interface {} 或具体结构体类型 #}These format verbs are very useful when troubleshooting template issues and understanding data structures.
**Practical Tips and Considerations
- Understanding format definitions:Mastering Go language
fmt.Sprintfformat verbs are efficient to usestringformatare the key. Commonly used include:%dDecimal integer%fFloating point number (can be combined.Control precision, such as%.2f)%sString%tBoolean%vDefault representation of the value%#vGo syntax representation of the value%TType of the value%%Literal percentage sign
- Type matching is fundamental:Ensure that the format verb you use matches the actual data type of the variable. For example, use for an integer.
%fThis may result in unexpected outcomes, and vice versa. - Pay attention to the filling order of multiple variables:When there are multiple placeholders in the format definition, the filter will fill in the variables provided after the format definition in the order from left to right.
- Default HTML escaping:
stringformatThe content output by the filter is defaultarily escaped in HTML to prevent XSS attacks. If the formatted result in your case indeed contains HTML tags and you want them to be parsed by the browser rather than displayed as plain text, remember to instringformatafter adding|safeFilter. - moderate use:For simple variable output or string concatenation,
{{变量}}or{{变量1}} {{变量2}}it may be more concise.stringformatSuitable for complex scenarios that require precise control of formatting, alignment, or combining multiple data types.
PassstringformatFilter, it allows the data display of the website to be more unified and professional, bringing a smoother and more accurate experience for both users and internal debugging.
Common Questions (FAQ)
Q1:stringformatand directly outputting variables{{ 变量 }}What is the difference?
A1:The variable will usually be displayed in its default string form, for example, floating-point numbers may show a long decimal place, or boolean values may be displayed astrue/false.stringformatFilters allow youprecise controlHow these variables are converted to strings, including decimal places, zero-padding for integers, prefixes and suffixes, to ensure that the data is displayed in a way that is more in line with business logic and user habits.
Q2: I want to format the date and time,stringformatCan I use it?
A2: stringformatTheoretically, it can be used for formatting Go languagetime.TimeA variable of type, but AnQi CMS provides more specialized and convenient date-time formatting tags: stampToDateThe tag directly accepts timestamps and Go language time format strings, making it more intuitive, for example.{{stampToDate(item.CreatedTime, "2006-01-02 15:04")}}We recommend using it first.stampToDateto handle date and time.
Q3: When I usestringformatWhat happens when the format definition does not match the variable type?