How to define the `stringformat` filter using Go's `fmt.Sprintf` format?

Calendar 👁️ 57

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:

  1. 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 #}
      
  2. Boolean format (%t)

    • %t: withtrueorfalseto output the boolean value.
      
      {# 假设有一个布尔变量 item.IsPublished = true #}
      <span>是否发布:{{ item.IsPublished|stringformat:"%t" }}</span>
      {# 输出:是否发布:true #}
      
  3. Integer format (%d,%x,%b)

    • %dOutput decimal integer.
      
      <span>产品ID:{{ item.Id|stringformat:"产品编号:%d" }}</span>
      {# 输出:产品ID:产品编号:1001 #}
      
    • %xOutput lowercase hexadecimal representation.
    • %bOutput binary representation.
  4. Floating-point format (%f,%e,%E)

    • %fOutput standard decimal floating-point number, default precision is 6 decimal places.
      
      {# 假设有一个浮点数变量 item.Price = 19.995 #}
      <span>价格:{{ item.Price|stringformat:"%.2f" }}</span>
      {# 输出:价格:19.99 (四舍五入) #}
      
      Here%.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 #}
      
  5. 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语言\"模板\"技巧" #}
      
  6. 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>
      {# 输出:名称:产品名称   #}
      

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 throughstringformatStandardize 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:

  • withfloatformatDifference: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.
  • withdate/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.

Related articles

How to use the `stringformat` filter to format a floating-point number as a string with two decimal places?

In website content display, accurate and unified number presentation is crucial for user experience.For example, displaying product prices on e-commerce websites or presenting statistical percentages in data reports may result in excessively long decimal places if floating-point numbers are displayed without processing, which may appear unprofessional and untidy.AnQi CMS as an efficient content management system provides powerful template functions, among which the `stringformat` filter is a powerful tool to solve this problem.

2025-11-08

What is the practical use of the `dump` filter in AnQi CMS template debugging?

During the development and maintenance of Anqi CMS templates, we often encounter situations where some data cannot be displayed correctly or the variable structure does not match the expected one.How can one quickly and effectively find the source of the problem, which is a challenge facing every template developer.Fortunately, AnQi CMS provides an extremely useful tool—the `dump` filter, which can help us penetrate the true appearance of variables in the template like X-ray.What is the `dump` filter?

2025-11-08

How to display document, category, or single page associated image groups (such as Banner galleries) in Anqi CMS template?

At the time of building a website, exquisite image sets, such as carousel banners, are important elements to attract visitors' attention and display core content.AnQiCMS (AnQiCMS) provides flexible and powerful template functions, allowing you to easily display these groups of images associated with documents, categories, or single pages on the website.This article will delve into how to call and display these image groups in Anqi CMS templates, helping you better utilize visual content to enhance the attractiveness of your website.---###

2025-11-08

How to list all documents under a specific tag in AnQi CMS template and support pagination?

In a content management system, effectively organizing and displaying articles is the key to improving user experience.When content is categorized through tags, we often need to list all the articles under a specific tag on a page, and to maintain the cleanliness and loading speed of the page, pagination functionality also becomes indispensable.Strong and flexible template tags provided by AnQi CMS make this requirement easy to achieve.

2025-11-08

How to remove specific characters or spaces from the beginning and end of a string in AnQiCMS template?

When using AnQiCMS for website content management, we often encounter situations where we need to refine the output strings in the template.For example, the text obtained from the database may contain unnecessary leading and trailing spaces, or in some specific scenarios, it may be necessary to remove the specific symbols from the beginning or end of the string to ensure the neat display of the page and the uniformity of data format.The powerful template engine of AnQi CMS provides a variety of practical filters that can easily handle these string processing requirements.

2025-11-08

How to display the latest published article list on the homepage of AnQiCMS?

In Anqi CMS, the homepage carries the important responsibility of attracting visitors and displaying the latest news.Generally, displaying the latest list of published articles in a prominent position on the homepage is an effective way to enhance user experience and guide content browsing.AnQi CMS with its flexible template system and powerful content management features makes this operation very direct and efficient.

2025-11-08

How to customize the title display format of AnQi CMS article detail page?

The secret to flexibly customizing the CMS article detail page title display formatIt not only affects the identification of users in browser tabs and favorites, but is also one of the key elements of search engine optimization (SEO).A clear, attractive, and well-formatted title that can effectively improve the click-through rate of the article and the professional image of the website.

2025-11-08

How to call and display custom parameter fields of articles in the Anqi CMS template?

In AnQi CMS, the custom parameter field of the article is an important manifestation of its core feature of 'flexible content model'.It allows us to define unique additional attributes for different types of content (such as articles, products), greatly enhancing the expressiveness of content and the customization capabilities of the website.Imagine if your website needs to display product details, in addition to the general information such as title, content, and images, you may also need specific parameters such as 'model number', 'color', 'storage capacity', and so on.These are the places where custom parameter fields take effect.

2025-11-08