In Anqi CMS template design, the flexibility of data display is a key aspect that template developers pay great attention to.The system is built-in with multiple filters (Filters) to process and format variables. Among them,stringformatThe filter is a versatile tool, it allows us to use Go languagefmt.SprintfThe powerful format definition of the function to accurately control the output form of any type of data, whether it is a number, a string, or a more complex data structure, it can be displayed in the expected style.
What isstringformatFilter?
stringformatThe filter is a general-purpose tool provided by the Anqie CMS template engine, its core function is to convert any type of value (such as integers, floating-point numbers, booleans, strings, even structs) into a string according to the specified format and output it. Its strength lies in its format definition syntax, which is consistent with the standard library of the Go language.fmt.SprintfThe function is consistent, which means users familiar with Go language formatting rules can easily handle it, even if they are not familiar, understanding its common patterns can also greatly enhance the expression ability of the template.
Deep Understanding: Go Languagefmt.SprintfFormatting Definition
Go languagefmt.SprintfFunctions are a very flexible string formatting tool, guiding how data is converted to text through a series of "format verbs" (Verb). These format verbs are usually prefixed with a percent sign (%Starting with a parenthesis followed by a letter or symbol, indicating the data type and required output style.
The followingstringformatCommon format verbs in Go language used in filters and their application scenarios:
General format (
%v,%+v,%#v,%T)%v: The default format for values. It is the most commonly used verb and can naturally output most types of values.{# 假设有一个整数变量 item.Views = 1234 #} <span>浏览量:{{ item.Views|stringformat:"%v" }}</span> {# 输出:浏览量:1234 #}%+vWhen outputting a structure, the field names and their values will be printed. It is very useful for debugging complex data structures.{# 假设有一个结构体变量 item.Category = {Id: 1, Title: "新闻"} #} <span>分类详情:{{ item.Category|stringformat:"%+v" }}</span> {# 输出:分类详情:{Id:1 Title:新闻} #}%#vOutput the value expressed in Go syntax. This format is very intuitive for debugging the structure of variables in Go.{# 假设有一个结构体变量 item.Category #} <span>Go语言表示:{{ item.Category|stringformat:"%#v" }}</span> {# 输出:Go语言表示:main.Category{Id:1, Title:"新闻", Link:"/news"} #}%TThe type of the output value. This can help us quickly identify it when the variable type is uncertain.<span>变量类型:{{ item.Views|stringformat:"%T" }}</span> {# 输出:变量类型:int #}
Boolean format (
%t)%t: withtrueorfalseto output the boolean value.{# 假设有一个布尔变量 item.IsPublished = true #} <span>是否发布:{{ item.IsPublished|stringformat:"%t" }}</span> {# 输出:是否发布:true #}
Integer format (
%d,%x,%b)%dOutput decimal integer.<span>产品ID:{{ item.Id|stringformat:"产品编号:%d" }}</span> {# 输出:产品ID:产品编号:1001 #}%xOutput lowercase hexadecimal representation.%bOutput binary representation.
Floating-point format (
%f,%e,%E)%fOutput standard decimal floating-point number, default precision is 6 decimal places.
Here{# 假设有一个浮点数变量 item.Price = 19.995 #} <span>价格:{{ item.Price|stringformat:"%.2f" }}</span> {# 输出:价格:19.99 (四舍五入) #}%.2fMeans retaining two decimal places. We can control%Nfto control the total width and precision.%e/%E: In scientific notation (eorEOutput in parentheses format.{# 假设有一个大数字变量 item.LargeNumber = 1234567890.12 #} <span>科学计数:{{ item.LargeNumber|stringformat:"%e" }}</span> {# 输出:科学计数:1.234568e+09 #}
String format (
%s,%q)%sOutput string.<span>文章标题:{{ item.Title|stringformat:"《%s》" }}</span> {# 输出:文章标题:《Go语言模板技巧》 #}%qOutput a quoted string, special characters will be escaped. It is very useful when a string needs to be output as part of code or script.{# 假设 item.Title 包含特殊字符 #} <span>带引号标题:{{ item.Title|stringformat:"%q" }}</span> {# 输出:带引号标题:"Go语言\"模板\"技巧" #}
Control of width and precision
- Add a number before the format verb to control the minimum width of the output, default is right-aligned, and the insufficient part is filled with spaces. For example
%5dWill format the number to at least 5 characters wide.<span>编号:{{ item.ID|stringformat:"%05d" }}</span> {# 用0填充左侧,如 00001 #} {# 输出:编号:00010 #} - Add a negative sign at the width (
%-5s) to achieve left alignment.<span>名称:{{ item.Name|stringformat:"%-10s" }}</span> {# 输出:名称:产品名称 #}
- Add a number before the format verb to control the minimum width of the output, default is right-aligned, and the insufficient part is filled with spaces. For example
stringformatFilter applications in AnQi CMS
stringformatFilters are widely used in the template development of AnQi CMS:
- Uniform data display formatWhether it is product price, inventory quantity, or statistical data, it can be displayed through
stringformatStandardize the format, for example, all prices should be rounded to two decimal places, and all quantities should be displayed as integers. - Debug template variables: When you are unsure of a variable's value or type, you can use
{{ myVar|stringformat:"%#v" }}or{{ myVar|stringformat:"%T" }}Quickly output its structure or type on the page, helping you quickly locate the problem. - Generate dynamic textCombine other variables to dynamically construct a text with a specific format. For example, generate a report summary containing multiple data items.
- Combine with HTML attributesIn some cases, it may be necessary to format numbers or strings as attribute values of HTML tags.
stringformatDifferences and similarities with other filters
AnQi CMS provides many filters, understanding the differences between them helps to choose the appropriate tools more efficiently:
- with
floatformatDifference:floatformatThe filter is specifically used for formatting floating-point numbers, it mainly focuses on retaining decimal places and rounding off. AndstringformatIt is more general, as it can handle floating-point numbers as well as format integers, strings, booleans, and provide more detailed control over width, alignment, etc. If it is only about handling decimal places of floating-point numbers,floatformatIt may be more concise, but if you need more complex number or text formatting,stringformatIs a better choice. - with
date/stampToDateDifference:dateandstampToDateThe filter is specifically used for date and time formatting.dateThe input is atime.Timetype, andstampToDateIt is convenient to handle Unix timestamps (10-digit integers). Although theoreticallystringformatCan also format Unix timestamps as numbers, but the output will be the number itself, not a specific date-time format (such as "2006-01-02 15:04:05"), so when dealing with date and time,dateorstampToDateIt is a more professional and recommended tool. - With other string processing filters:
replaceUsed to replace specific substrings in strings,cutUsed to remove characters,addUsed for concatenating strings or numbers. These filters focus on the content of the strings.modifywhilestringformatThey focus on the content.Formatted presentation, both have different responsibilities and can be used together.