In the AnQiCMS template, flexible control over the format of data output is the key to content presentation. 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 -stringformatA filter. It is like a precise converter that can take different types of values and output them as neat and uniform strings according to the rules you define.

Deep understandingstringformatFilter

stringformatThe basic usage of the filter is{{ obj|stringformat:"格式定义" }}. Here,objrepresents the variable you want to format, and"格式定义"It is the core, which determines the final style of the output. Developers familiar with the Go language may find that this filter is similar to the built-in features of Go language.fmt.Sprintf()Functions have the same effect, which means they inherit 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 to a specific width, or present a string in a different way.This is particularly important when displaying prices, dates, counts, or any data that requires a uniform style on a website.

Common formatting options and applications

Let's look at some specific examples to seestringformatHow does the filter handle different data types:

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

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

  • %vOutput the value of the variable in the default format. This is the most general option and is suitable for almost all types.
  • %+vWhen outputting a struct, it will include the field names.
  • %#vOutput the value of a variable in Go language syntax, very useful for debugging complex structures.
  • %TOutput the type of a variable in Go language.

Example:Assume you have a document object.archiveWould you like to view its ID and title?

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

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

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

  • %dOutput decimal integer.
  • %fOutput a floating-point number.
  • %.2fControl the decimal precision of a floating-point number, for example.%.2fmeans retaining two decimal places.
  • %eor%EOutput a floating-point number in scientific notation.
  • %xor%XOutput the hexadecimal representation.

Example:Assumearchive.PriceIs a floating-point number,archive.ViewsIt is 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 a string (%s,%q)

When processing strings, in addition to basic output, special formatting is sometimes also required.

  • %s: Output the original value of the string.
  • %q:Output 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.SiteNameIt is the name of the website,archive.KeywordsA 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 the neat formatting of tables or lists.

  • %Ns: Right-align the string and fill the left side with spaces to make its total width reach N characters.
  • %-NsLeft-justify a string and fill with spaces on the right to make its total width N characters.
  • %0NdRight-align the integer 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 displayed.product.Code(For example)123), and it should always be displayed as a 5-digit number, with leading zeros.

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

Summary

stringformatThe filter is a very practical tool in AnQiCMS template development.It allows you to finely control the output format of the data, thereby improving the readability and professionalism of the website content.By flexible application%v,%d,%.2f,%sFormat options, you can convert the original data into a user-friendly display form without modifying the backend code, and complete all presentations directly in the template layer.Mastering its use will enable you to soar in the content operation of AnQiCMS.


Frequently Asked Questions (FAQ)

Q1:stringformatFilters andaddWhat are the differences between filters?

A1:stringformatFilters are mainly used forFormatVariableDisplay methodConvert it to a string in a specific format. It does not perform mathematical operations or logical concatenation, but focuses on 'how it looks'. AndaddFilter is used forPerform addition operation, whether it is the sum of numbers or the concatenation of strings. For example,{{ 5|add:2 }}It will output.7while{{ "hello "|add:"world" }}It will output.hello world. The two functions are different and should not be confused.

Q2: I tried to usestringformatformat an empty value ornilWhy is there no output or strange values were output?

A2: WhenstringformatThe filter receives an empty value (such asnilOr an empty string, zero-value number) depends on the format definition you use. For example,%vMay output in Go language,nilThe default representation (such as<nil>or an empty string), whereas%.2fFormatnilor0It may output0.00. If you wish to display a default friendly text when a 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 supported formatting options?

A3: BecausestringformatThe filter is based on Go languagefmt.Sprintf()and therefore it supports allfmt.Sprintf()The formatting options. You can refer to the Go language official documentation aboutfmtpackage's detailed explanation, especiallyPrintfThe series function's formatting verb part, where all available options such as types, widths, precision, and flags are listed for more advanced customization.