The `stringformat` filter provides which advanced string formatting options (such as number precision, alignment style)?

Calendar 👁️ 72

In the powerful template system of AnQi CMS, we often need to present dynamic data on the website, and the way the data is displayed directly affects user experience and the efficiency of information communication. To present numbers, texts, and other content in a more professional and clear manner, AnQi CMS providesstringformatA filter, it is like a multifunctional formatting tool that can help us finely control the display details of content.

stringformatA filter plays a role similar to Go language in AnQi CMS.fmt.Sprintf()The role of a function, which means it has rich formatting options, far more than simple string replacement.By using it, we can directly perform complex formatting operations on variables in the template, such as controlling the decimal precision of numbers, adjusting the alignment of text, and applying specific display rules based on different data types.

Precision control of the decimal point accuracy of numbers

It is crucial to control the number of decimal places in scenarios where prices, percentages, or any precise numerical values are displayed.stringformatThe filter provides flexible numeric precision control, ensuring your data is both accurate and beautiful.

For example, when we have a floating-point number3.141592653In order to display only two decimal places on the page, you can use it like this:

{{ 3.141592653|stringformat:"%.2f" }}
{# 显示结果:3.14 #}

here,%.2fof.2Specified to retain two decimal places,fRepresents formatting a number as a floating-point number. If you need to keep one decimal place, just.2changed to.1The system will round it automatically. For example,123.4567Formatted as%.1fwill be displayed123.5This precise control ensures that financial data, scientific data, and so on are presented in a standardized manner, avoiding visual confusion caused by redundant decimals.

Flexible text alignment and filling settings

In addition to numerical precision, the alignment of content and whitespace padding also significantly affects the overall layout of the page, especially when constructing tables or columnar layouts.stringformatThe filter can help us easily align text to the left and right and fill with fixed width.

By default, when you specify a width for a string or number,stringformatit will align contentto the rightAlign and fill spaces on the left to reach the specified total width. For example, if we want a string to be right-aligned within 15 characters:

{{ "AnQiCMS"|stringformat:"%15s" }}
{# 显示结果:        AnQiCMS (AnQiCMS前面有8个空格) #}

Here%15sIt indicates that the string will besFormatted to a width of 15 characters. If the original string is not long enough, the blank part will be filled with spaces on the left.

If you want to contentLeft-alignedAnd fill in the space on the right, we can add a negative sign before the width (-):

{{ "AnQiCMS"|stringformat:"%-15s" }}
{# 显示结果:AnQiCMS        (AnQiCMS后面有8个空格) #}

This alignment method is very practical when displaying list items, product names, or any text that needs to be neatly arranged, as it ensures good visual consistency within a fixed area.

These alignment and padding options can also be combined with number formatting. For example, a floating-point number needs to be left-aligned and retain two decimal places:

{{ 123.456|stringformat:"%-10.2f" }}
{# 显示结果:123.46    (数字后有4个空格) #}

Formatting of diverse data types

stringformatThe strength lies in its support for Go languagefmt.SprintfRich formatting verbs, which means it can handle various data types and output in the way you need.

Some common formatting verbs include:

  • %d: Formatted as a decimal integer.
  • %s: Formatted as a basic string.
  • %t: Formatted as a boolean value (true/false).
  • %xor%XFormat as lowercase or uppercase hexadecimal.
  • %for%e/%EFormat as a floating-point number or in scientific notation.
  • %vFormat as the default representation of the value, suitable for any type.

For example, convert an integer to hexadecimal:

{{ 255|stringformat:"%x" }}
{# 显示结果:ff #}

Or embed a boolean value in a description:

{{ true|stringformat:"当前状态: %t" }}
{# 显示结果:当前状态: true #}

These flexible options allow you to choose the most suitable formatting method based on the actual data content and display requirements, thus avoiding manual concatenation or complex conditional judgments, greatly simplifying the template code.

Practical scenario: Create a professional product display

Imagine you are building a product list page that needs to display the product name, price, and inventory. In order to present this information in a uniform and professional manner, we can use a combination ofstringformatThe various functions:

{% set productName = "高性能服务器" %}
{% set productPrice = 1999.99 %}
{% set productStock = 75 %}

<p>产品名称:{{ productName|stringformat:"%-20s" }}</p>
<p>价格:{{ productPrice|stringformat:"%-10.2f" }} 元</p>
<p>库存:{{ productStock|stringformat:"%5d" }} 件</p>

This code will display the following effect (assuming each character width is consistent):

产品名称:高性能服务器       
价格:1999.99     元
库存:   75 件

By uniformly setting the width of strings, the precision of floating-point numbers, and the alignment of integers, even if the data length is different, it can maintain visual neatness and consistency, greatly enhancing the user's reading experience.

In conclusion, in AnQi CMSstringformatThe filter is a powerful and highly flexible tool. It helps us go beyond simple content display, through numerical precision control, alignment adjustment, and varied data type formatting, transforming raw data into beautifully typeset, clear information website content.Master and make good use of these advanced formatting options, no doubt, it will enable your security CMS website to rise to a higher level in visual presentation and information delivery, bringing users a better browsing experience.


Frequently Asked Questions (FAQ)

1.stringformatandfloatformatWhat are the differences between the filters? Which one should I choose?

floatformatThe filter is mainly used for the formatting of floating-point numbers, its functions are relatively concentrated, mainly solving the problem of retaining decimal places of floating-point numbers (including rounding) and displaying zero values. AndstringformatFilter is a more general formatting tool, which not only supports floating-point numbers, but also handles integers, strings, boolean values and other data types, and provides more rich formatting options such as number accuracy, text alignment, padding characters, etc. If your requirement is limited to the decimal places of floating-point numbers,floatformatMay be more concise; but if necessary

Related articles

How to use the `slice` filter to extract a specified range of characters or elements from a string or array?

In the process of creating AnQiCMS templates, it is essential to be able to flexibly handle strings and arrays.Whether it is to display the article summary or to extract part of the elements from the list, the `slice` filter can provide powerful and convenient help.It allows you to extract specific ranges of characters from strings or select elements from arrays at specified positions, making content display more accurate and diverse.What is the `slice` filter?In simple terms, the `slice` filter is like a precise pair of scissors

2025-11-08

What are the differences between `trim`, `trimLeft`, and `trimRight` filters in removing whitespace or specific characters from a string?

In website content management, we often encounter situations where we need to clean and format strings, such as removing extra spaces at the beginning and end of user input text, or standardizing data with specific prefixes or suffixes.AnQiCMS provides a series of powerful template filters to simplify these operations, among which `trim`, `trimLeft`, and `trimRight` are powerful tools for handling string leading and trailing characters.They have similar functions but have different scopes.

2025-11-08

How to limit the display length of the link text when converting URLs with the `urlizetrunc` filter?

In AnQiCMS (AnQiCMS) content operation practice, we often encounter some details that require fine-grained processing, one of which is how to elegantly display the super-long URL on the page.When a text contains a long URL, it may destroy the page layout and affect the overall aesthetics and the reading experience of the user.Fortunately, Anqi CMS provides the `urlizetrunc` filter, which can help us easily solve this problem, allowing URLs to be converted into clickable links while still controlling their display length

2025-11-08

How does AnQiCMS automatically identify URL links in text and convert them into clickable `<a>` tags?

During content creation and publication, we often encounter situations where we need to cite external sources or share relevant links.If these URLs are in plain text form, users not only need to manually copy and paste them, but it will also affect the reading experience and the professionalism of the website.Anqi CMS knows this pain point, and therefore integrated the intelligent URL automatic recognition and conversion function from the beginning of the system design, making your content publishing more efficient and convenient, and improving the user experience accordingly.### Intelligent recognition, automatic conversion: Say goodbye to manual operation AnQi CMS through its powerful template engine

2025-11-08

How to repeat a string a specified number of times, for example, to display a welcome message repeatedly?

In website content operations, we often encounter situations where we need to repeat certain information, such as repeating copyright information in the footer, playing a greeting phrase in the welcome area repeatedly, or adding visual separators between list items.Copying and pasting manually is not only inefficient but also very麻烦 when it needs to be modified.Luckyly, AnQiCMS's powerful template engine provides a simple and efficient way to solve this problem, one very practical feature is the `repeat` filter.###

2025-11-08

What risks should be noted when using the `safe` filter to prevent XSS attacks in AnQiCMS templates?

AanQi CMS has always paid great attention to security from the very beginning, which is fully reflected in its concise and efficient Go language architecture, aiming to provide users with a secure and stable content management environment.In the daily content publishing and template creation, we often come across various template tags and filters.Among them, the `safe` filter is a powerful tool but also one that requires our special vigilance.It allows us to output raw HTML content in the template, but it is precisely this 'freedom' that hides some risks that should not be overlooked, especially in preventing cross-site scripting (XSS) attacks.

2025-11-08

How to use the `escapejs` filter to safely embed template variables into JavaScript code?

In the daily use of AnQi CMS, we often need to display the content of the background management, such as article titles, user comments, or other dynamic data, on the front-end page.This content is not just plain text, it also needs to be used in JavaScript code, such as variable values, function parameters, or dynamically generated HTML fragments.However, embedding template variables directly into JavaScript code, if not handled properly, may introduce a significant security vulnerability - cross-site scripting (XSS)

2025-11-08

How do the `center`, `ljust`, and `rjust` filters control the alignment of a string within a specified width?

In website content management, we often need to present text in an orderly and beautiful manner, especially when dealing with specific layouts or content that requires structured display.AnQiCMS's template engine provides several very practical string filters, specifically used to control the alignment of text within a fixed width. They are `center`, `ljust`, and `rjust`.Understand and make good use of them, which can help us control the display effect of the front-end page more finely.### Center the string with `center`

2025-11-08