How to use the `stringformat` filter to generate a numeric string with leading zeros or a specific width in AnQi CMS (such as order numbers)?

Calendar 👁️ 69

In website operations, we often need to handle various numerical strings with specific formats, such as order numbers, product codes, or member IDs.These numbers usually need to maintain a certain length, and leading zeros are used to fill in when the numbers are insufficient to ensure uniformity and aesthetics.AnQiCMS (AnQiCMS) provides a very practical template filter——stringformatCan help us easily meet these needs.

UnderstandingstringformatThe role of the filter

stringformatThe filter plays a role in data formatting in Anqi CMS templates. Its working principle is similar to that in Go language.fmt.Sprintf()The function is very similar, able to convert different types of data (such as numbers, strings) into the final string format as specified.This means you can precisely control the way numbers are displayed, such as fixed width, leading zero padding, etc.

stringformatusage

UsestringformatThe basic syntax of the filter is very intuitive:

{{ obj|stringformat:"格式定义" }}

here,objThis is the variable or value you want to format, and"格式定义"It is a string that contains the rules you want the data to present.

The key to mastering number formatting: leading zeros and specific width

For generating numbers like order numbers that have leading zeros or specific widths, we need to understand some commonly used format specifiers:

  1. Integer type (d): dIs used as a type identifier for formatting decimal integers.
  2. Minimum width (x):In%anddInsert a number betweenx, indicating the minimum width of the output string. If the length of the number itself is less thanxIf it will be filled.
  3. Leading zero padding (0):If the minimum width digitxIs added in front of0For example%0xd, then when the number length is insufficientxWhen, the system will use leading zeros instead of spaces for padding.

Example: Generate numbers with leading zeros.

Suppose we want a number to always be displayed as 5 digits, with leading zeros if it is less than 5 digits:

{{ 123|stringformat:"%05d" }}

The output of the above code will be:00123.

Example: Generate a number with a specific width and fill with spaces

If we don't add0it will be filled with spaces by default:

{{ 123|stringformat:"%5d" }}

The output of the above code will be:123(There are two spaces in front).

In the actual application of the Anqi CMS template

Imagine you are building an order detail page for a website, and you need to display a standardized order number, or display a product ID with a fixed number of digits in a product list. At this point,stringformatit comes in handy.

Scenario one: Format the document ID as an order number or product code

In Anqi CMS, documents (archive) Typically, it has a unique ID. We can use this ID to generate numbers with prefixes and leading zeros.

For example, get the ID of a document, format it as a 6-digit number with leading zeros, and add the prefix "ORD-":

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
        <div>
            <!-- 假设 item.Id 是一个订单ID,比如 1 -->
            订单号:ORD-{{ item.Id|stringformat:"%06d" }}
        </div>
    {% endfor %}
{% endarchiveList %}

Ifitem.IdIs1The output will be:订单号:ORD-000001Ifitem.IdIs12345The output will be:订单号:ORD-012345.

This ensures that regardless of the length of the ID, the final order number maintains a uniform length and format.

Scenario two: Format custom fields

If you define a custom numeric field in the content model, such as "Product Batch Number", you can also format it:

{% archiveDetail product_info with name="BatchNumber" %}
    <!-- 假设 BatchNumber 是一个数字,比如 789 -->
    产品批次号:BATCH-{{ product_info|stringformat:"%04d" }}
{% endarchiveDetail %}

IfBatchNumberIs789The output will be:产品批次号:BATCH-0789.

Combined with other template tags and variables

stringformatThe filter can be flexibly combined with other safe CMS template tags and filters.You can format the ID of each item in the loop and also assign the formatted result to a new variable for reuse in other parts of the template.

{% set raw_id = item.Id %}
{% set formatted_order_id = raw_id|stringformat:"%06d" %}
<div>
    格式化后的订单ID:ORD-{{ formatted_order_id }}
</div>

Summary

BystringformatThe filter, Anqi CMS provides a powerful and flexible tool for content operators and template developers, allowing precise control over the display format of numbers on the page. Whether it's creating a unified order number, product code, or any other numeric string that requires a fixed length and leading zero padding,stringformatCan help you a hand, making the website content more professional and standardized.

Frequently Asked Questions (FAQ)

Q1:stringformatandaddWhat are the differences between filters?A1:stringformatThe filter is mainly used to convert data (such as numbers or strings) into a string output according to predefined format rules, focusing on format control, such as zero-padding, fixed width, decimal places, etc. AndaddThe filter is used to add two numbers together or concatenate two strings, it focuses on numerical calculations or string concatenation operations.

Q2: If I want to format a variable that is not a numeric type but uses%dsuch a numeric format character, what will happen?A2:stringformatThe filter tries to perform type conversion internally. If your variable is a string representation of a number (such as '123'), it usually converts it to a number correctly and according to%dFormat. But if the variable is a completely non-numeric string (for example, "hello"), then use%dThis could result in output of0Or an empty string, the specific behavior depends on the internal implementation. To ensure accuracy, it is best to confirm the type of the variable or use a more general%s(string) format symbol.

Q3: How to add a custom prefix to a formatted number string, such as 'ORD-' or 'SKU-'?A3: In the Anqi CMS template, you can directly instringformatConcatenate the output result of the filter externally. For example, if you want to add the prefix "ORD-" to a formatted number, you can write it like this:ORD-{{ item.Id|stringformat:"%06d" }}The filter will first complete the formatting of the number, and then the result will be connected with the 'ORD-' string.

Related articles

Does the `stringformat` filter support custom internationalization format output for datetime objects?

In the daily operation of the website, we often need to display date and time information in a user-friendly manner.Especially when facing users from different regions, it is particularly important to be able to output date and time formats that conform to local customs, which is what we commonly refer to as 'internationalized format output'.Today, let's talk about a commonly used filter `stringformat` in AnQiCMS, and see if it supports this customized internationalized format output for date and time objects.

2025-11-08

In the Anqi CMS backend custom field, if a field stores a URL, how can you use the `stringformat` filter to validate its format in the template?

Storing URLs in the AnQiCMS backend custom fields is a very practical feature, allowing us to add various personalized information to content models based on business needs.However, when these URLs need to be displayed in front-end templates, we not only need to ensure that they can be output correctly, but sometimes we also hope to perform some basic format checks to enhance the robustness and user experience of the page.

2025-11-08

Can the `stringformat` filter convert a Go language slice or Map into a readable JSON string output?

When developing templates for AnQiCMS, we often encounter such questions: The background data is a slice (Slice) or map (Map) structure in Go language, and if we want to output these data in a readable JSON string format in the front-end template, can the `stringformat` filter built into AnQiCMS handle it?This is indeed a very practical requirement, after all, JSON format is ubiquitous in modern web development.

2025-11-08

How to safely handle user input that may contain JS code in the comment or message form of Anqi CMS using the `escapejs` filter?

In website operation, the comment area and message board are important channels for interacting with users and collecting feedback.However, this area where users can freely enter content is often an entry point for potential security risks, especially cross-site scripting (XSS) attacks.As website administrators, we must ensure that the content entered by users is safe when displayed on the frontend and is not exploited maliciously.The Anqi CMS, a system focused on providing secure and efficient content management solutions, has provided us with powerful tools to meet such challenges. Today

2025-11-08

In AnQi CMS template, how to automatically get the thumbnail version of a dynamically generated image URL (such as `{{item.Logo}}`) through the `thumb` filter?

In website content operation, images are an indispensable element to enhance user experience and convey information.However, how to ensure the quality of images while also considering the loading speed and layout beauty of the website, especially in the case of a large number of images with dynamic sources, has become a challenge for many operators.AnQiCMS as an efficient and flexible content management system provides us with an elegant solution, including the `thumb` filter for handling dynamic image URLs and automatically retrieving thumbnails.Why do we need thumbnails? We all know

2025-11-08

Does the `thumb` filter in AnQi CMS support specifying the width and height of the thumbnail, or only fetching the cropped URL?

When using Anqi CMS for website content management, we often need to handle images, especially thumbnails for articles or products.This is when the `thumb` filter comes into play.It can help us easily generate and obtain the thumbnail address from a complete image address.However, many friends may be curious, does this `thumb` filter support specifying the width and height of thumbnails directly when used?Or is it just returning a cropped image URL?

2025-11-08

How to use the `stringformat` filter in Anqi CMS templates combined with `if` tags to output different string descriptions based on the value size?

In website operation, we often encounter the need to dynamically adjust the display content of the page based on data.For example, a product page may display "Sufficient stock", "Tight stock" or "Temporarily out of stock" based on the inventory quantity; a user points page may display "Regular member", "Senior member" or "VIP member" based on the points level.

2025-11-08

How to use the `repeat` filter in Anqi CMS template to quickly generate repeated placeholders or decorative strings?

In AnQi CMS template design, flexibly using various filters (Filter) is the key to improving template performance and development efficiency.Among them, the `repeat` filter provides a very convenient solution for quickly generating repetitive placeholders or decorative strings with its concise characteristics.`repeat` filter, as the name implies, is mainly used to repeat a specified string or variable content according to the number of times set.

2025-11-08