In AnQiCMS templates, flexibly controlling the format of data output is the key to content presentation. In order to ensure that various data types (whether they are numbers, text, or more complex structures) can be displayed to visitors in the way you expect, AnQiCMS provides a powerful and practical tool —stringformatFilter. It acts like a precise converter, able to output different types of values into neat, unified strings according to your defined rules.

Deep understandingstringformatFilter

stringformatThe basic usage of the filter is{{ obj|stringformat:"格式定义" }}Here,objrepresents the variable you want to format, and"格式定义"The core is where it is, it determines the final output style. Developers familiar with the Go language may find that this filter is similar to the built-in Go language.fmt.Sprintf()Functions have the same effect as different tunes, which means it inherits the strong capabilities and rich options of Go language in formatting output.

UtilizestringformatYou can easily round a floating-point number to two decimal places, pad an integer value to a specific width, or present a string in a different way.This is particularly important for displaying prices, dates, counts, or any data that requires a uniform style on the website.

Common formatting options and applications

Let's take a look at some specific examples, to seestringformatHow filter handles different data types:

1. General types and debugging information (%v,%+v,%#v,%T)

Sometimes, you may not be sure of the specific content or type of a variable, or you may need to display it in the most generic way.

  • %vThis outputs the value of the variable in the default format. It is the most general option and applies to almost all types.
  • %+vWhen a struct is output, it will include the field names.
  • %#v:Output the value of the variable in Go language syntax, very useful for debugging complex structures.
  • %T:Output the Go language type of the variable.

Example:Assume you have a document objectarchive,You want to view its ID and title.

{# 输出文档ID的默认值 #}
<div>文档ID:{{ archive.Id|stringformat:"%v" }}</div>
{# 输出文档标题的类型 #}
<div>文档标题类型:{{ archive.Title|stringformat:"%T" }}</div>

2. Precise control of numbers (%d,%f,%e,%x)

For numeric types,stringformatprovides a rich set of control options, allowing you to accurately manage its display style.

  • %d:Output the decimal integer.
  • %f:Output floating-point numbers.
  • %.2f:Control the decimal precision of floating-point numbers, for example%.2findicating that two decimal places should be retained.
  • %eor%E:Output floating-point numbers in scientific notation.
  • %xor%X:Output in hexadecimal representation.

Example:Assumearchive.Priceis a floating-point number,archive.Viewsis an integer.

{# 价格保留两位小数 #}
<div>商品价格:{{ archive.Price|stringformat:"%.2f" }} 元</div>
{# 浏览量以整数形式输出 #}
<div>文章浏览量:{{ archive.Views|stringformat:"%d" }} 次</div>
{# 假设有一个十六进制ID #}
<div>文档内容的ID(十六进制):{{ archive.Id|stringformat:"%x" }}</div>

3. Flexible display of strings (%s,%q)

When processing strings, in addition to the basic output, special formats are sometimes also needed.

  • %s: Output the original value of the string.
  • %qThis outputs a string enclosed in double quotes. This is very useful when generating JavaScript code or when it is necessary to clearly distinguish the boundaries of strings.

Example:Assumesystem.SiteNameIs the name of the website,archive.KeywordsIt is a string of keywords.

{# 网站名称直接输出 #}
<div>网站名称:{{ system.SiteName|stringformat:"%s" }}</div>
{# 关键词带引号输出,便于在JS中使用 #}
<div>关键词:{{ archive.Keywords|stringformat:"%q" }}</div>

4. Width and Alignment (%5s,%-5s,%05d)

In addition to type and precision, you can also control the output width and alignment, which is very useful for neat formatting of tables or lists.

  • %Ns:Align a string to the right and fill it with spaces on the left to make it N characters wide.
  • %-NsAlign a string to the left and fill the right side with spaces to make its total width N characters.
  • %0NdAlign an integer to the right, and fill it with zeros on the left to make its total width reach N characters (often used for dates, numbers, etc.).

Example:Assume you have a product number that needs to be displayedproduct.Code(For example}]}123),and it is always displayed as 5 digits, with leading zeros if necessary

{# 产品编号不足5位时左侧补零 #}
<div>产品编号:{{ product.Code|stringformat:"%05d" }}</div>
{# 将网站名称左对齐,总宽度为20个字符 #}
<div>{{ system.SiteName|stringformat:"%-20s" }}</div>

Summary

stringformatThe filter is a very practical tool in the AnQiCMS template development.It allows you to finely control the output format of data, thereby improving the readability and professionalism of the website content.%v,%d,%.2f,%sFormat options, you can convert the original data to a user-friendly display format without modifying the backend code, and complete all presentation needs directly at the template level.Master its usage, and it will give you an edge in the content operation of AnQiCMS.


Common Questions (FAQ)

Q1:stringformatfilters andaddWhat are the differences between filters?

A1:stringformatFilters are mainly used forFormattedVariablesDisplay mode,Convert it to a string in a specific format. It does not perform mathematical operations or logical concatenation, but focuses on 'how it looks'.addis used for filteringto perform addition operations,Whether it is the sum of numbers or the concatenation of strings. For example,{{ 5|add:2 }}It will output7while{{ "hello "|add:"world" }}It will outputhello world. They have different functions and should not be confused.

Q2: I tried to usestringformatto format a null value ornilWhy is there no output or strange values are output?

A2: EnglishstringformatThe filter receives an empty value (such asnilor an empty string, zero value numbers) its output behavior depends on the format definition you are using. For example,%vit may output in Go language,nilthe default representation (such as<nil>or an empty string), while%.2fFormattednilor0it may output0.00. If you want to display a default friendly text when the variable is empty, it is recommended to usedefaulta filter to provide a backup value, for example{{ your_variable|default:"暂无数据"|stringformat:"%s" }}.

Q3: Where can I findstringformatall formatting options supported?

A3: Sincestringformatthe filter is implemented in Go languagefmt.Sprintf()therefore it supports allfmt.Sprintf()The format options. You can refer to the official Go language documentation forfmtdetailed information about the package, especiallyPrintfThe formatting verb part of the series functions, where all available options such as types, widths, precision, and flags are listed, allowing for more advanced customization.