In Anqi CMS template development, we often need to display various data obtained from the background in a specific and beautiful format to website visitors.Whether it is the price of goods, the reading volume of articles, or the balance of users' points, the original presentation of the data may not always be ideal. At this time,stringformatThe filter has become a very practical tool.
stringformatThe filter can help us format numbers, variables, and even more complex structures according to the string pattern we preset.In simple terms, it is like a professional typesetter who can 'beautify' original data into unified and standardized text form according to the provided 'typesetting instructions'.Understand and make good use of this filter, it can 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 with Go languagefmt.Sprintf()The function is closely related. This means that if you are familiar with the formatting string syntax in the Go language, then you can usestringformatThe filter will be effortless. Even if you are not familiar with it, by some common format definitions (also known as "format verbs"), you can quickly master its use.
Its basic syntax is very intuitive:
{{ 变量 | stringformat:"格式定义" }}
Here变量It is the data you want to format, while格式定义It is a string containing special symbols, which tell the filter how to process and display your variables.
Common application scenarios
stringformatThe filter is widely used in the display of website content, here are some of the most common examples:
1. Precisely control the display of numbers
Numbers are one of the most commonly formatted data types, especially when it comes to currencies, percentages, or specific precision requirements.
Format floating-point numbers: When we need to display product prices, discount percentages, or numbers that require fixed decimal places,
stringformatthey come in handy. For example,%.2fRepresents 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
%frepresents floating-point numbers,.2Specified to retain two decimal places,%%It represents a literal percentage sign.Format an integer:Ensure that the integer data does not have a decimal point, or display it with a specific width.
%dIs a common format verb for integers.{% set articleViews = 12345 %} {% set productStock = 88 %} <p>文章阅读量:{{ articleViews | stringformat:"%d" }}</p> {# 输出:文章阅读量:12345 #} <p>库存数量:{{ productStock | stringformat:"%03d" }}</p> {# 输出:库存数量:088 (使用0填充到3位宽度) #}%03dof0Indicates zero-padding,3Indicates total width of 3 digits.
2. Constructing dynamic strings and combining information
stringformatEffectively helps us combine different types of data to generate more readable description text.%sUsed for general string replacement,%vIs the default representation of a value.
Combining 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, separated by commas.Display complex objects or debug information:Sometimes, when debugging templates, you need to view the internal structure of a complex object (such as a structure, array):
%v/%#vand%Tit can be put to use.{% 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 in troubleshooting template problems and understanding data structures.
**Practice and Precautions
- Understand the definition of format:Master Go language
fmt.SprintfThe format verbs are efficient to use.stringformatThe key. Commonly used include:%dDecimal Integer%fFloating Point (can combine.Control precision, such as%.2f)%sString%tBoolean Value%vDefault representation of value%#vGo syntax representation of value%TType of value%%Literal percentage sign
- Type matching is fundamental:Make sure the verb you use matches the actual data type of the variable. For example, use
%fmay result in unexpected outcomes, and vice versa. - Pay attention to the order of filling multiple variables:When the format definition contains multiple placeholders, the filter will use the variables provided after the format definition in order from left to right to fill in.
- Default HTML escaping:
stringformatThe output of the filter is default HTML-escaped to prevent XSS attacks. If the formatted result of your indeed contains HTML tags and you want them to be parsed by the browser rather than displayed as plain text, remember tostringformatthen add|safefilter. - Use moderately:For simple variable output or string concatenation, use it directly
{{变量}}or{{变量1}} {{变量2}}It may be more concise.stringformatIt is suitable for complex scenarios that require precise control of format, alignment, or combination of multiple data types.
BystringformatFilter, you can make the data display of the website more unified and professional, whether it is for users or internal debugging, it can bring a smoother and more accurate experience.
Frequently Asked Questions (FAQ)
Q1:stringformatAnd output variables directly{{ 变量 }}What is the difference?
A1:Variables are usually output in their default string form, for example, floating-point numbers may display a long decimal place, or boolean values may be displayed astrue/falseHoweverstringformatFilters allow youPrecise controlHow do these variables get converted to strings, including decimal places, zero-padding for integers, prefixes and suffixes, etc., 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 dates and times,stringformatCan I use it?
A2: stringformatTheoretically, it can be used for formatting Go languagetime.TimeType variables, but Anqi CMS provides more specialized and convenient date-time formatting tags:stampToDate. This tag directly accepts timestamps and Go language date format strings, making it more intuitive, for example{{stampToDate(item.CreatedTime, "2006-01-02 15:04")}}. We recommend using it firststampToDateto handle date and time.
Q3: When I usestringformatWhat happens when the format definition does not match the variable type?