In the template design of AnQi CMS, the flexibility of data display is a very important aspect that template developers pay great attention to.The system is built-in with various filters (Filters) to process and format variables.stringformatThe filter is a versatile tool, it allows us to use Go languagefmt.SprintfThe powerful format definition of the function to precisely control the output form of any type of data, whether it is numbers, strings, or more complex data structures, they can be displayed in the expected style.
What isstringformatFilter?
stringformatThe filter is a general-purpose tool provided by the Anqin CMS template engine, which core function is to convert any type of value (such as integers, floating-point numbers, boolean values, strings, and even structs) into a string according to the specified format and output it. Its strength lies in the format definition syntax which is consistent with the standard library of the Go language.fmt.SprintfThe function is completely consistent, which means that users familiar with the Go language formatting rules can easily handle it, and even those who are not familiar with it can greatly enhance the expressiveness of the template by understanding its common patterns.
Deep Understanding: Go Languagefmt.SprintfFormatting Definition
Go language'sfmt.SprintfFunction is a very flexible string formatting tool that uses a series of "format verbs" (Verb) to direct how data is converted to text. These format verbs are usually prefixed with a percent sign (%The beginning with a parenthesis, followed by a letter or symbol, is used to indicate the data type and required output style.
The followingstringformatSome commonly used Go language format verbs in filters and their application scenarios:
通用格式 (English)
%v,%+v,%#v,%T)%v:值的默认格式。这是最常用的动词,能以自然的方式输出大多数类型的值。English{# 假设有一个整数变量 item.Views = 1234 #} <span>浏览量:{{ item.Views|stringformat:"%v" }}</span> {# 输出:浏览量:1234 #}%+vWhen outputting a structure, it will print the field names and their values of the structure. It is very useful when debugging complex data structures.{# 假设有一个结构体变量 item.Category = {Id: 1, Title: "新闻"} #} <span>分类详情:{{ item.Category|stringformat:"%+v" }}</span> {# 输出:分类详情:{Id:1 Title:新闻} #}%#v:Output the value represented by Go syntax. This format is very intuitive for debugging variable structures in the Go language.{# 假设有一个结构体变量 item.Category #} <span>Go语言表示:{{ item.Category|stringformat:"%#v" }}</span> {# 输出:Go语言表示:main.Category{Id:1, Title:"新闻", Link:"/news"} #}%T:Output value type. This can help us quickly identify it when the variable type is uncertain.<span>变量类型:{{ item.Views|stringformat:"%T" }}</span> {# 输出:变量类型:int #}
Boolean format (
%t)%t:Usingtrueorfalseto output boolean values.{# 假设有一个布尔变量 item.IsPublished = true #} <span>是否发布:{{ item.IsPublished|stringformat:"%t" }}</span> {# 输出:是否发布:true #}
Integer format (
%d,%x,%b)%d:Output the decimal integer.<span>产品ID:{{ item.Id|stringformat:"产品编号:%d" }}</span> {# 输出:产品ID:产品编号:1001 #}%x:Output the lowercase hexadecimal representation.%b:Output the binary representation.
Float number format (
%f,%e,%E)%f:Output standard decimal floating-point number, default precision is 6 decimal places.
Here{# 假设有一个浮点数变量 item.Price = 19.995 #} <span>价格:{{ item.Price|stringformat:"%.2f" }}</span> {# 输出:价格:19.99 (四舍五入) #}%.2fto retain two decimal places. We can use%Nfto control the total width and precision.%e/%E:in scientific notation (eorEEnglish format output{# 假设有一个大数字变量 item.LargeNumber = 1234567890.12 #} <span>科学计数:{{ item.LargeNumber|stringformat:"%e" }}</span> {# 输出:科学计数:1.234568e+09 #}
String format output
%s,%q)%sOutput string.<span>文章标题:{{ item.Title|stringformat:"《%s》" }}</span> {# 输出:文章标题:《Go语言模板技巧》 #}%q:Output a string with double quotes; special characters will be escaped. It is very useful when outputting a string as part of code or script.{# 假设 item.Title 包含特殊字符 #} <span>带引号标题:{{ item.Title|stringformat:"%q" }}</span> {# 输出:带引号标题:"Go语言\"模板\"技巧" #}
Width and precision control
- Add a number before the format verb to control the minimum width of the output. The default is right-aligned, and insufficient parts are filled with spaces. For example
%5dThe number will be formatted to at least 5 characters wide.<span>编号:{{ item.ID|stringformat:"%05d" }}</span> {# 用0填充左侧,如 00001 #} {# 输出:编号:00010 #} - Add a negative sign before the width (
%-5s) can achieve left alignment.<span>名称:{{ item.Name|stringformat:"%-10s" }}</span> {# 输出:名称:产品名称 #}
- Add a number before the format verb to control the minimum width of the output. The default is right-aligned, and insufficient parts are filled with spaces. For example
stringformatThe actual application of the filter in AnQi CMS
stringformatThe filter has a wide range of applications in the template development of AnQi CMS:
- Unified data display format: Whether it is product price, inventory quantity or statistical data, it can be displayed through
stringformatFormat consistently, for example, all prices should be rounded to two decimal places, and all quantities should be displayed as integers. - Debug template variablesWhen you are uncertain about the value or type of a variable, 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 HTML attributesIn some cases, it may be necessary to format numbers or strings as attributes of HTML tags.
stringformatDifferences and similarities with other filters
The Auto CMS provides many filters, understanding the differences between them helps to choose the appropriate tools more efficiently: English
- With
floatformatdifferences:floatformatThe filter is specifically designed for the formatting of floating-point numbers, focusing mainly on the retention of decimal places and rounding.stringformatIt is more general, as it can handle floating-point numbers as well as format integers, strings, boolean values, and provide more detailed control over width and alignment. If it is only about handling the decimal places of floating-point numbers,floatformatMay be more concise, but if more complex numerical or text formatting is required,stringformatthis is a better choice. - With
date/stampToDatedifferences:dateandstampToDateThe filter is specifically used for date and time formatting.dateThe input required is atime.Timethe type, andstampToDatethen conveniently handles Unix timestamps (10-digit integers). Although theoreticallystringformatThe output will be the number itself, not a specific date and time format (such as "2006-01-02 15:04:05"), therefore, when handling date and time,dateorstampToDateIt is a more professional and recommended tool. - Than other string processing filters:
replaceUsed to replace specific substrings in strings,cutUsed to remove characters,addUsed to concatenate strings or numbers. These filters focus on the content of strings.Modifywhilestringformatwhich focuses on the content.Formatted presentation, both of which have different responsibilities and can be used together.