In the display of website content, we often need to present different types of data (such as numbers, strings, and even more complex structures) in a unified and accurate manner on the page. The template engine of AnQiCMS provides powerful tools for this, one of which is a very practical feature isstringformatFilter, it helps us format any value into a string output of a specific format.
When we retrieve data from the background, whether it is the number of views of articles, the price of products, or user-defined parameters, they may exist in the form of numbers, boolean values, or raw strings.But the front-end page often has specific requirements for displaying these data, such as prices need to be kept with two decimal places, percentages do not need decimal places, or certain data need to be displayed with prefixes and suffixes.stringformatThe filter is particularly important, as it acts like a professional 'data beautician', able to modify various data according to our wishes, into strings that best meet the display requirements.
For users familiar with the Go language AnQiCMS,stringformatthe way of working will be very friendly, because it is consistent with the built-in of the Go language,fmt.Sprintf()The function is very similar, controlled by a set of formatting verbs (format verbs) to control output.This means you can take advantage of the powerful formatting capabilities of the Go language to implement complex data display logic in the AnQiCMS template.
How to usestringformatFilter?
stringformatThe basic usage of the filter is very intuitive:
{{ 要格式化的值|stringformat:"格式定义" }}
Here:
要格式化的值is any variable or literal that you want to format, it can be a number, string, boolean, or even complex data structures."格式定义"is a string that contains the instructions on how you want to format the value, which are the formatting verbs we mentioned earlier.
Below are some commonly used formatting verbs and their application scenarios:
String (
%s)This is the basic format of the verb used to convert any value to a string.It is very useful when you need to convert non-string values to strings, or to embed other strings in a string.{% set articleTitle = "安企CMS入门指南" %} <p>{{ articleTitle|stringformat:"文章标题:%s" }}</p> {# 输出: 文章标题:安企CMS入门指南 #}Integer (
%d): 专为整数值设计。如果你想确保数字以纯整数形式显示,或者在数字前后添加特定文本,可以使用它。{% set viewCount = 12345 %} <p>浏览量:{{ viewCount|stringformat:"%d 次" }}</p> {# 输出: 浏览量:12345 次 #} {% set productId = 888 %} <p>产品编号:{{ productId|stringformat:"P-%d" }}</p> {# 输出: 产品编号:P-888 #}浮点数 (
%f,%.NF)Process numbers with decimals.%fFloating-point numbers will be displayed with the default precision,%.NFThis can precisely control the number of decimal places and round off. This is the most commonly used method in scenarios such as displaying prices, ratios, etc.{% set productPrice = 99.998 %} <p>价格:{{ productPrice|stringformat:"%.2f 元" }}</p> {# 输出: 价格:100.00 元 (进行四舍五入) #} {% set discountRate = 0.85 %} <p>折扣:{{ discountRate|stringformat:"%.0f%%" }}</p> {# 输出: 折扣:85% (注意这里需要先将0.85转换成85再格式化) #}Supplementary notes: If you need to
0.85格式化为English85%English usually needs to perform multiplication first:{{ (discountRate * 100)|stringformat:"%.0f%%" }}.Universal value (
%v,%+v,%#v): These are very powerful formatting verbs, especially suitable for debugging or when it is necessary to display the original structure information of variables.%v:以默认格式打印值。%+v:当打印结构体时,会打印字段名及其值。%#v:打印Go语言语法表示的值,对于结构体,会显示其类型和字段。%T:Print the type of the value in Go language.
{# 假设有一个名为 article 的复杂对象 #} <p>文章对象详情:{{ article|stringformat:"%v" }}</p> <p>文章对象类型:{{ article|stringformat:"%T" }}</p> {# 这在调试时非常有用,可以直观地查看变量内容和类型 #}
Combined with the actual application of AnQiCMS template tags
stringformatIts strength lies in the fact that it can be used with various data retrieval tags in AnQiCMS (such asarchiveDetail/system/contactSeamlessly combine .
For example, get the website name from the system settings and format it for output:
{% system siteName with name="SiteName" %}
<title>{{ siteName|stringformat:"%s - 我们的网站" }}</title>
{# 假设siteName是"安企CMS",输出: <title>安企CMS - 我们的网站</title> #}
Or on the document detail page, format the document's view count into a more user-friendly display:
{% archiveDetail views with name="Views" %}
<p>本文已有 {{ views|stringformat:"%d 人阅读" }}</p>
{# 假设views是500,输出: <p>本文已有 500 人阅读</p> #}
By flexibly using these formatting verbs, we can present any data obtained from the AnQiCMS backend in the most suitable string format for the user interface and business logic, greatly enhancing the professionalism and user experience of the website content.
Common Questions (FAQ)
1.stringformatandstampToDateWhat is the difference? When should I use them?
stringformatis a general-purpose string formatting tool that can handle various types of data such as numbers and strings.stampToDateis a tag specifically used to format a 10-digit Unix timestamp into a date-time string. If you need to format a timestamp into a readable date format, you should usestampToDateIf you need to perform generic string formatting for other types of values, or need to control the precision, prefix, and suffix of numbers, then usestringformat.
2. When I want to format a floating-point number and control the number of decimal places, I should choosestringformatOrfloatformatWhat are the differences?Both can be used to format floating-point numbers and control the number of decimal places.
stringformat:"%.2f"Will strictly follow the Go language'sfmt.Sprintf()formatting rules, regardless of the number of decimal places in the original number, it will always output two decimal places (for example10Will become10.00,9.998Will become10.00).floatformat:2(or specify other numbers) is also used for floating-point formatting, it will retain the specified number of decimal places, but has a feature that if the last digit is 0, it may not be displayed (for example10.00it will be displayed as10,9.998becomes10.00)。Furthermore,“floatformatSupports negative digit places, used to truncate from the right. In summary, if you needStrict and alwaysDisplay the specified number of decimal places (even if it is zero),stringformatMore reliable; if you wish toKeep the decimal places displayed more 'naturally' while maintaining accuracy.(For example, omitting trailing zeros),floatformatmay be more suitable.
3.stringformatCan it be used to truncate long strings?
stringformatIt is mainly used forFormatted,instead ofTruncated.Although you can indirectly affect the output length by using some complex formatting verbs (such as combining width limits), this is usually not its **purpose.truncatecharsortruncatewordsFilters, they are more professional and convenient for handling such needs.