In the AnQi CMS template, the precise display of data is a key element in improving user experience and the professionalism of the website.stringformatThe filter is exactly such a tool that allows us to format various types of data in a highly flexible manner to meet diverse front-end display needs. It draws on the powerful features of the 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 define a variable in a specified format and convert it to a string output. Its basic usage is to append it to the variable.|stringformat:"格式定义"English translation of 'auto' is 'English'.This allows us to present numbers, boolean values, strings, and even complex data structures in a unified and controlled manner on the page.

For example, if we have a variable namedproductPriceThe variable, if you want to format it as currency with two decimal places, you can write it like this:{{ productPrice|stringformat:"%.2f" }}.

stringformatFormatting verbs supported by Go language for the filter

stringformatThe filter supports a series of formatting verbs in Go language, each suitable for different data types and display requirements. Mastering these verbs is the foundation for precise control of output format.

  1. Common output verb (%vSeries):

    • %v: The most commonly used general format, which will output according to the default representation of the variable.UsageId
    • %+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 Go language syntax, which is very useful for debugging or understanding data structures.
    • %T:Outputs the Go language type of a variable, which is particularly helpful for debugging and development.
  2. Basic type output verb:

    • Integer type:
      • %d: Format the integer as a decimal representation. For example,100auto English100.
      • %b: Format the integer as a binary representation. For example,99auto English1100011.
      • %c:Interpret the integer as a Unicode code point and output the corresponding character. For example,99auto Englishc.
      • %x(lowercase) /%X(uppercase):Format the integer into hexadecimal representation. For example,99auto English63.
    • Floating point type:
      • %fStandard decimal floating-point format. For example,3.14159auto English3.141590.
      • %e(lowercase) /%E(Uppercase): Scientific notation. For example,123400000.0auto English1.234000e+08.
    • Boolean type:
      • %tFormat the boolean value astrueorfalse.
    • String type:)
      • %s: Basic string output, often used to display text content.
      • %qLike the Go source code, the string output with double quotes. It is very useful for distinguishing between raw strings and formatted strings.
    • Pointer type:
      • %p:Output the value of a pointer, usually representing a memory address. It is not directly used in front-end templates, but understanding its existence is very beneficial.
  3. Width and precision control:in many numerical verbs (such as%f/%dBefore ,you can add numbers to control the output width and precision.

    • %W.Pf:WRepresents the total width.PRepresents the precision after the decimal point. For example,%.2findicating that two decimal places should be retained.
    • %*W.Pf: Use*You 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 effect. The following are some common application scenarios and suggestions:

  1. 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 **select**.

    <p>文章ID:{{ article.Id|stringformat:"%d" }}</p>
    <p>阅读量:{{ article.Views|stringformat:"%d" }}</p>
    
  2. Show currency, price, or percentage:Scenarios involving amounts or requiring precise decimal places,%fThe precision control of verb combination is particularly important. Usually, we hope the currency is accurate to two decimal places.

    <p>商品价格:¥{{ product.Price|stringformat:"%.2f" }}</p>
    <p>折扣率:{{ discountRate|stringformat:"%.1f" }}%</p>
    
  3. 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 powerful 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>
    
  4. Dynamic text composition and descriptive output:When you need to embed variables in strings or create descriptive output containing text, you can directly combine text with%scombined with verbs.

    <p>{{ article.Title|stringformat:"最新文章:‘%s’" }}</p>
    <p>{{ userName|stringformat:"欢迎用户:%q 登录" }}</p> {# 使用%q可以确保用户输入原样显示,包含引号 #}
    
  5. strings that handle special characters:If the string may contain special characters, it should be displayed as is, especially for data coming from user input, use%qThe output can automatically add quotes, which is sometimes helpful to avoid confusion or debugging problems.

Useful Tips:

  • Combine|safeFilter:IfstringformatThe content 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 instead of being displayed as plain text. Remember tostringformatAfter chaining addition|safeFilter, for example{{ content|stringformat:"%s"|safe }}.
  • Type matching principle:Even though the formatting verbs of the Go language have some error tolerance to some extent (for example, when formatting strings to numbers, zero may be obtained), it is best to match the selected formatting verb with the actual data type of the variable to ensure the accuracy of the output.
  • Dynamic values and static formats: stringformatthe format definition part is a string,