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 precise manner on the page. AnQiCMS (AnQiCMS) provides powerful tools for this, one of which is a very practical feature that isstringformatA filter that helps us format any value as a string in a specific format.
When we retrieve data from the backend, whether it is the number of views of an article, the price of a product, 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 some data need to be displayed with prefixes and suffixes. At this time,stringformatThe filter is particularly important, as it is like a professional 'data整形师', able to modify various data according to our wishes, shaping it into the most suitable string for display.
For users familiar with AnQiCMS in Go language,stringformatthe working style will be very familiar, because it is consistent with the built-infmt.Sprintf()The function is very similar, controlled by a set of format verbs to control the 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?
stringformatbasic usage of the filter is very intuitive:
{{ 要格式化的值|stringformat:"格式定义" }}
Here:
要格式化的值is any variable or literal 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 values, these instructions are the formatting verbs mentioned earlier.
Here are some commonly used formatting verbs and their application scenarios:
String (
%s)This is the most basic formatting 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 within a string.{% set articleTitle = "安企CMS入门指南" %} <p>{{ articleTitle|stringformat:"文章标题:%s" }}</p> {# 输出: 文章标题:安企CMS入门指南 #}Integer (
%d): Designed for integer values. If you want to ensure that numbers are displayed in pure integer form or to add specific text before or after the number, you can use it.{% set viewCount = 12345 %} <p>浏览量:{{ viewCount|stringformat:"%d 次" }}</p> {# 输出: 浏览量:12345 次 #} {% set productId = 888 %} <p>产品编号:{{ productId|stringformat:"P-%d" }}</p> {# 输出: 产品编号:P-888 #}Floating point number (
%f,%.NF)Handling numbers with decimals.%fWill display floating-point numbers with the default precision, and%.NF(where N is a number) it is possible to accurately 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 explanation: If you need to convert
0.85Formatted as85%Multiply first:{{ (discountRate * 100)|stringformat:"%.0f%%" }}.Universal value (
%v,%+v,%#v)These are very powerful formatting verbs, especially for debugging or displaying the original structure of variables.%v: Prints the value in the default format.%+v: When printing a struct, it will print the field names and their values.%#v: Prints the value in Go language syntax representation, for structs, it will display the type and fields.%TPrint the Go language type of the value.
{# 假设有一个名为 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/contactCombine seamlessly
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, format the number of views of the document more friendlily on the document detail page:
{% archiveDetail views with name="Views" %}
<p>本文已有 {{ views|stringformat:"%d 人阅读" }}</p>
{# 假设views是500,输出: <p>本文已有 500 人阅读</p> #}
By flexibly using these formatting verbs, we can display any data obtained from the AnQiCMS backend in the string format that best fits the user interface and business logic, greatly enhancing the professionalism and user experience of the website content.
Frequently Asked Questions (FAQ)
1.stringformatandstampToDateWhat is the difference? When should I use them?
stringformatIt is a general string formatting tool that can handle various types of data such as numbers, strings, and more.stampToDateIs a label specifically used to format a 10-digit Unix timestamp into a datetime string. If you need to format a timestamp into a readable date format, you should usestampToDateIf you need to format strings for other types, or need to control the precision, prefix, and suffix of numbers, then usestringformat.
2. When I want to format floating-point numbers and control the number of decimal places, I should choosestringformatOrfloatformat? What are the differences between them?Both can be used to format floating-point numbers and control the number of decimal places.
stringformat:"%.2f"Strictly adheres to 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 number formatting, it retains the specified number of decimal places, but there is a feature that if the last digit is 0, it may not be displayed (for example10.00It will be displayed as10,9.998becomes10.00)。In addition,floatformatIt also supports negative number of digits, used to truncate from the right. In summary, if you needStrict and alwaysDisplay decimal places to the specified number (even if it is zero),stringformatMore reliable; if you want toDisplay decimal places more "naturally" while maintaining accuracy(For example, omitting trailing zeros),floatformatMaybe this is more appropriate.
3.stringformatCan be used to truncate long strings?
stringformatMainly used forFormatinstead ofTruncate. Although you can indirectly affect the output length with some complex formatting verbs (such as combining width limits), this is usually not its purpose.If you need to truncate a long string and add an ellipsis at the end (such as “…”), it is recommended to use the template provided in AnQiCMStruncatecharsortruncatewordsFilters, they are more professional and convenient for handling such needs.