In AnQiCMS template development, in order to better display and control the way data is presented on the page, we often need to format variables.stringformatFilter is a very practical tool, it allows us to convert numbers, strings, or other types of values to a specific string format according to predefined rules. The strength of this filter lies in its adoption of the Go language.fmt.Sprintf()The placeholder syntax of the function makes the control of output format both flexible and precise.

stringformatThe filter supports multiple placeholders, which can meet the formatting needs of different data types. Understanding these common placeholders can help us present website content more efficiently and beautifully.

General placeholder

These placeholders are applicable to any type of data, they will try to 'print' variables in different ways:

  • %vThis is the most basic placeholder, it 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 structures (such as document objects, category objects, etc. in AnQiCMS)%+vIt will output its value as well as the field name, which is very useful for debugging and allows you to clearly see the names of each attribute and their corresponding values.
  • %#vThis placeholder will output the Go language representation of the value, including type information and field names.This is very helpful for deep understanding of the underlying structure and type of variables, especially when debugging template rendering issues.
  • %TIf you just want to know what the Go language type of a variable is,%Tit can be useful. It will directly output the type name of the variable, for example,int/string/structetc.

number placeholder

for numbers,stringformatProvided multiple ways to control their display:

  • %d: Used to output decimal integers. No matter your number isintOruint, it 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,%.2findicating that two decimal places should be retained.
  • %eor%E:If you need to represent floating-point numbers in scientific notation, you can use these placeholders.%eUse lowercasee,%EUse uppercaseE.
  • %b:Convert numbers 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 provide additional control:

  • %sThe most commonly used string placeholder, which directly outputs the string content.
  • %q:Output the string literal with double quotes. If the string itself contains special characters,%qIt will be properly escaped to ensure the output conforms to the Go language's string literal specification.

Width and precision control

In addition to the placeholder itself, we can also control the width and precision of the output by adding numbers before the placeholder:

  • Width controlAdd 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, it will be filled with spaces on the left; if it exceeds 5 digits, it will be displayed normally.
  • Precision control:For floating-point numbers, you can use.a number before the placeholder to control the number of decimal places, for example%.2fthe floating-point number will be formatted to retain two decimal places.
  • combined width and precisionBoth can be used together, such as%5.2fMeans the total width is at least 5 digits, with two decimal places retained.
  • Left aligned:By default, when the width is insufficient, the text is right-aligned and spaces are filled on the left. If you want to align the text to the left, you can add-for example%-5sto align the string to the left and fill spaces on the right.

Actual application example

We assume we have a product objectproductwhich includesPrice(float),Stock(integer) andName(string) etc. 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" }}

Through the above examples, you can seestringformatFilter can provide powerful formatting capabilities in actual development.No matter it is to beautify the data visible to the user or to quickly view the detailed information of variables in the development debugging process, it is an indispensable tool.


Common Questions (FAQ)

  1. 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 accordance with specific string patterns, with placeholder syntax based on the Go language.fmt.Sprintf.stampToDateThe filter is specifically used to handle timestamps, converting Unix timestamps to readable date and time formats, and supporting Go language standard time format strings as arguments. In short, stringformatIt is a general-purpose formatting tool,stampToDateIt is a tool specializing in timestamp conversion.

  2. What will happen if the formatted value type does not match the placeholder completely? stringformatFilter at the bottom attempts to perform type conversion to match the placeholder, but if the conversion fails, its behavior may vary due to Go languagefmt.SprintfThe specific implementation varies. In most cases, Go will attempt to provide a reasonable default output (for example, using strings as%dformatted output may result in 0 or an error message, using numbers as%s格式化则会输出数字的字符串形式),但这种情况下,输出结果可能不是你所期望的,甚至可能导致模板渲染错误。因此,在使用EnglishstringformatAt the time, it is recommended to ensure that the placeholder you choose is as compatible as possible with the actual data type of the variable.

  3. Besides what is mentioned in the article, are there any otherstringformatadvanced usage or tips? stringformatas the Go languagefmt.SprintfThe encapsulation, its advanced usage is basically consistent with the formatting rules of the Go language. For example, you can use%symbols to customize the padding characters%05dRepresentation of filling with zeros to 5 digits, or controlling the precision of floating-point numbers outputed%.nfwhere,nfor the number of decimal places). In addition, combiningstringformatYou can build very complex dynamic content display logic with other logic judgments or loop tags of AnQiCMS template. It is recommended to consult the official Go language documentation regardingfmt.SprintfThe detailed explanation to explore more advanced techniques.