How does the `stringformat` filter output values of different data types in a custom format?

Calendar 👁️ 73

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.

Related articles

How does the `count` filter count the occurrences of a specific keyword in a string or array?

In AnQi CMS template development, efficiently handling and analyzing content is the key to enhancing website interactivity and information display capabilities.Sometimes, we need to know how many times a specific word appears in a piece of text, or how many times a specific element is included in a data list.This is when the `count` filter comes into play.It is a very practical tool that can help us quickly count the occurrences of a specific keyword in a string or an array (slice).

2025-11-07

The `contain` filter how to determine if a string or array contains a specified keyword?

In Anqi CMS template development, flexibly controlling the display of content is the key to improving website user experience and operational efficiency.Sometimes, we may need to determine whether a piece of text, a list (array), or a data object (Map/Struct) contains a specific keyword or property.At this time, the `contain` filter provided by Anqi CMS can give full play to its role, it can help us easily achieve this kind of conditional judgment, making the template logic more intelligent.What is the `contain` filter?

2025-11-07

How `length` and `length_is` filters are used to check the length of a string, array, or map?

In Anqi CMS template development, flexible handling and displaying data is the key to improving website interactivity and user experience.Understanding how to efficiently detect the length of strings, arrays, or mappings (similar to dictionaries or associative arrays in other programming languages) is the foundation for content operations and template customization.This article will introduce in detail the `length` and `length_is` practical filters in the Anqi CMS template engine, which will help you better control the display of page content.### `length` filter

2025-11-07

How `default` and `default_if_none` filters set a default display value for possibly empty variables?

In website content management, we often encounter situations where variable values may be empty.These empty values, if displayed directly on the front-end page, may lead to incomplete content display, page layout disorder, and even a bad user experience.AnQiCMS (AnQiCMS) as a powerful content management system, the Django template engine syntax it adopts provides us with a flexible way to handle such issues.

2025-11-07

How does the `thumb` filter quickly generate and display a thumbnail version of the original image URL?

In website operation, images are key elements to attract users and enrich content, but large image files often slow down page loading speed, affecting user experience and search engine optimization.Anqi CMS knows this and therefore provides a very convenient and efficient solution——the `thumb` filter.It can easily convert the original image into a thumbnail version suitable for web display, without manual processing, greatly enhancing the efficiency of content publication and the overall performance of the website.### Core Function Analysis: `thumb` Filter's Working Principle This is named

2025-11-07

How does AnQiCMS adaptively display website content for different devices (PC/Mobile end)?

In today's parallel network environment of multiple devices, users may access websites through desktop computers, laptops, tablets, or smartphones.Therefore, ensuring that the website content displays well on different devices and provides a smooth user experience is a key link in the success of website operation.AnQiCMS as an enterprise-level content management system fully considers this requirement and provides a flexible and diverse adaptive display scheme for device content, allowing users to choose the most suitable method according to their own situation.AnQiCMS mainly provides three core strategies for handling multi-device display of website content

2025-11-07

How to customize the display of SEO titles, keywords, and descriptions on the AnQiCMS homepage?

In the digital age, the homepage of a website is like the 'front door' of a company, the information presented to search engines is crucial.An meticulously optimized homepage that clearly conveys the core value of the website, attracts target users, and provides friendly crawling signals to search engines.In AnQiCMS, customizing the display of the SEO title (Title), keywords (Keywords), and description (Description) on the homepage is a straightforward and powerful process, which is an important manifestation of AnQiCMS's SEO-friendly features.

2025-11-07

How to customize the URL rewrite rules for the article detail page in the AnQiCMS template?

## Optimize SEO, Enhance User Experience: AnQiCMS Detailed Explanation of Custom Article Detail Page URL Static Rules In website operation, a clear and meaningful URL structure is crucial for search engine optimization (SEO) and user experience.Imagine a user sees `/article.php?Which link would be more attractive to them, the one with `id=123&category=news` such as this, or the one with `/news/anqicms-url-guide.html` such as this?

2025-11-07