In Anqi CMS template, the accurate display of data is a key factor in improving user experience and website professionalism.stringformatA filter is exactly such a tool, allowing us to format various types of data in a highly flexible way to meet the diverse needs of front-end display. It draws on the powerful features of Go language.fmt.SprintfFunction syntax allows developers and content operators to accurately control the format of the output content.
UnderstandingstringformatFilter
stringformatThe core function of the filter is to convert a variable into a string output according to a specified format. The basic usage is to append the variable with|stringformat:"格式定义"The format definition follows the formatting verbs of the Go language.This allows us to present numbers, booleans, strings, and even complex data structures in a unified and controllable manner on the page.
For example, if we have a file namedproductPriceThe variable, if you want to format it as currency with two decimal places, you can write it like this:{{ productPrice|stringformat:"%.2f" }}.
stringformatThe Go language formatting verbs supported by the filter
stringformatThe filter supports a series of formatting verbs in Go language, each of which is suitable for different data types and display requirements. Mastering these verbs is the basis for precise control of the output format.
General output verb (
%vseries):%v: The most commonly used general format, which will output according to the default representation of variables.%+vWhen the variable is a struct, it will output the field names and field values of the struct, providing more detailed information.%#v: Represents the output value of a variable in the Go language, which is very useful for debugging or understanding data structures.%T: Outputs the type of a variable in Go language, which is particularly helpful for debugging and development.
Basic type output verb:
- Integer type:
%d: Format the integer as a decimal representation. For example,100Output is100.%b: Format the integer as a binary representation. For example,99Output is1100011.%c: Interpret the integer value as a Unicode code point and output the corresponding character. For example,99Output isc.%x(lowercase) /%X(uppercase): Format the integer as a hexadecimal representation. For example,99Output is63.
- Floating point type:
%f: Standard decimal floating-point format. For example,3.14159Output is3.141590.%e(lowercase) /%E(Uppercase): Scientific notation. For example,123400000.0Output is1.234000e+08.
- Boolean type:
%t: Format boolean values astrueorfalse.
- String type:
%s: Basic string output, often used to display text content.%q: As in Go source code, output strings with double quotes. Very useful for scenarios that need to distinguish between raw strings and formatted strings.
- Pointer type:
%p: Output the value of a pointer, which usually represents a memory address. It is rarely used in front-end templates, but understanding its existence is very beneficial.
- Integer type:
Width and precision control:In many numerical verbs (such as
%f/%dBefore%W.Pf:WrepresentsPrepresents the precision after the decimal point. For example,%.2fmeans retaining two decimal places.%*W.Pf: Use.*can dynamically specify the width and precision.
How to choose the most suitable output format in Anqi CMS template?
Choose the appropriate formatting method, depending on the data type you want to display and the final visual presentation. The following are some common application scenarios and suggestions:
Display pure numbers (such as article ID, page views):When you need to display pure integer data such as article ID, user ID, page views, etc.,
%dThe verb is **choose.<p>文章ID:{{ article.Id|stringformat:"%d" }}</p> <p>阅读量:{{ article.Views|stringformat:"%d" }}</p>Display currency, price, or percentage:Involves amounts or requires precise decimal places,
%fIt is particularly important to combine action with precision control. Usually, we hope that currency is accurate to two decimal places.<p>商品价格:¥{{ product.Price|stringformat:"%.2f" }}</p> <p>折扣率:{{ discountRate|stringformat:"%.1f" }}%</p>Debug output or check data structure:During template development, if you need to understand the specific value, internal structure, or Go language type of a variable,
%vthe series of verbs will be your helpful assistant.%#vEspecially suitable for viewing complex structure variables, it can provide a representation similar to Go code.{# 输出变量的Go语言类型 #} <p>变量类型:{{ someVar|stringformat:"%T" }}</p> {# 输出结构体的详细信息(带字段名) #} <pre>{{ someComplexObject|stringformat:"%+v" }}</pre>Dynamic text combination and descriptive output:When you need to embed variables in a string or create output with descriptive text, you can directly combine text with
%setc. verbs.<p>{{ article.Title|stringformat:"最新文章:‘%s’" }}</p> <p>{{ userName|stringformat:"欢迎用户:%q 登录" }}</p> {# 使用%q可以确保用户输入原样显示,包含引号 #}To handle special characters in strings:If a string may contain special characters, it needs to be displayed as is, especially for data from user input, use
%qYou can automatically add quotes when outputting, which is sometimes helpful to avoid confusion or debugging issues.
Practical Tips:
- Combine
|safeFilter:IfstringformatThe content being output itself contains HTML tags (such as rich text content read from a database), and you want these HTML tags to be parsed by the browser rather than displayed as plain text. Remember tostringformatAfter chained addition|safeFilter, for example{{ content|stringformat:"%s"|safe }}. - Type matching principle:Although Go's formatting verbs have some tolerance in formatting (such as getting zero when converting strings to numbers), it is best to match the formatting verb with the actual data type of the variable to ensure the accuracy of the output.
- Dynamic values and static format:
stringformatThe definition part of the format is a string,