In AnQiCMS template development, in order to better display and control the presentation of data on the page, we often need to format variables. Among them,stringformatA filter is a very practical tool that allows us to convert numbers, strings, or other types of values into a specific string format according to predefined rules. The strength of this filter lies in its adoption of the Go language infmt.Sprintf()The syntax of placeholder function makes the control of output format flexible and accurate.
stringformatThe filter supports a variety of placeholders to meet the formatting needs of different data types. Understanding these common placeholders can help us present website content more efficiently and beautifully.
Generic placeholder
These placeholders are applicable to any type of data, they try to 'print' the variable in different ways:
%vThis is the most basic placeholder, which will output the variable in its default format. For example, an integer will be displayed in decimal, and a string will be output directly.%+vWhen processing a structure (such as the document object, category object, etc. in AnQiCMS), use%+vIt will output its value and also include the field name, which is very useful for debugging as it can clearly show each attribute's name and its corresponding value.%#vThis placeholder will output the Go representation of the value, including the type information and field name.This is very helpful for understanding the underlying structure and type of variables, especially when troubleshooting template rendering issues.%TIf you just want to know what the type of a variable in Go is,%Tit can be used. It will directly output the type name of the variable, for example,int/string/structetc.
numeric placeholder
for numbers,stringformatProvide multiple ways to control their display:
%dUsed to output decimal integers. No matter your number is:intOruintIt will be displayed in standard decimal form.%f: Used to output floating-point numbers (such as prices, percentages, etc.). You can control the number of decimal places by adding a precision modifier, for example%.2fmeans retaining two decimal places.%eor%E: If you need to represent floating-point numbers in scientific notation, you can use these placeholders.%eUse lowercasee,%EUse uppercaseE.%b: Convert the number to binary representation.%c:Interpret an integer value as a Unicode code point and output the corresponding character.%x:Convert a number to its hexadecimal representation.
String placeholder
When processing text content, these placeholders can provide additional control:
%sThe most commonly used string placeholder, directly outputs the string content.%qOutput a double-quoted string literal. If the string itself contains special characters,%qIt will be properly escaped to ensure the output conforms to the string literal specification of the Go language.
Control of width and precision
In addition to the placeholder itself, we can also control the output width and precision by adding numbers before the placeholder:
- Width control: Add a number between the placeholder and the percentage sign, for example
%5dThis indicates that the output number must occupy at least 5 characters in width. If the number itself is less than 5 digits, spaces will be filled on the left; if it exceeds 5 digits, it will be displayed normally. - Precision control: For floating-point numbers, you can use a placeholder before it
.to control the number of decimal places after the decimal point, for example%.2fit will format the floating-point number to retain two decimal places. - width and precision combinedBoth can be used together, such as
%5.2fIndicates that the total width is at least 5 digits, with two decimal places retained. - Left-alignedBy default, when the width is insufficient, it is right-aligned with spaces filled on the left. If you want to be left-aligned, you can add before the width number
-For example%-5sIt will make the string left-aligned with spaces filled on the right.
Actual application example
Assuming we have a product objectproductwhich includesPrice(a floating point number),Stock(Integer) andName(a string) and other properties. We hope to display the following information in the template:
商品名称:{{ product.Name|stringformat:"%s" }}
商品价格:{{ product.Price|stringformat:"¥%.2f" }}
剩余库存:{{ product.Stock|stringformat:"%d 件" }}
商品详情:{{ product.Description|stringformat:"商品描述: \"%q\"" }}
产品类型(调试用):{{ product|stringformat:"%T" }}
完整产品信息(调试用):{{ product|stringformat:"%+v" }}
As can be seen from the above examples,stringformatThe filter can provide powerful formatting capabilities in practical development.No matter whether it is to beautify the data visible to the user or to quickly view the detailed information of variables during development debugging, it is an indispensable tool.
Frequently Asked Questions (FAQ)
stringformatFilters andstampToDateWhat are the differences between filters?stringformatThe filter is mainly used to output various data types (such as numbers, strings, booleans, structs, etc.) in a specific string pattern, with the placeholder syntax based on the Go language'sfmt.SprintfHoweverstampToDateThe filter is specifically used to handle timestamps, converting Unix timestamps to readable date and time formats, and supporting the standard date format strings in Go language as parameters. In short, ...stringformatIs a general-purpose formatting tool,stampToDateIs specialized in timestamp conversion.What will happen if the formatted value type does not match the placeholder completely?
stringformatThe filter at the bottom attempts to perform type conversion to match the placeholder, but its behavior may vary due to Go languagefmt.SprintfThe specific implementation varies. Usually, Go will try to provide a reasonable default output (for example, wrapping strings in%dFormatting may result in 0 or an error message, using numbers instead%sFormatted, the string representation of a number will be output), but in this case, the output result may not be as expected, and even lead to template rendering errors. Therefore, when usingstringformatAt the same time, it is recommended to ensure that the placeholder selected is as compatible as possible with the actual data type of the variable.In addition to what is mentioned in the article, what are some about
stringformatadvanced usage or techniques?stringformatas a Go languagefmt.SprintfThe encapsulation, its advanced usage is basically consistent with the formatting rules of the Go language. For example, you can use%the symbol to define the padding character (%05dThis represents padding with zeros to 5 digits) or controlling the precision of the floating-point number output(%.nfof whichnfor the number of decimal places). Moreover, combinestringformatWith other logic judgments or loop tags of the AnQiCMS template, you can build very complex dynamic content display logic. It is recommended to consult the official Go language documentation aboutfmt.SprintfThe detailed description to explore more advanced techniques.