In website operation, 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.stringformatEnglish can help us easily achieve these needs.

UnderstandingstringformatThe role of the filter

stringformatThe filter plays a role in data formatting in the template of Safe CMS. Its working principle is similar to that in the 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 display of numbers, such as fixed width, leading zero padding, etc.

stringformatbasic usage

UsestringformatThe basic syntax of the filter is very intuitive:

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

Here,objIt is the variable or value you want to format, and"格式定义"is a string that contains the rules you want the data to be presented in.

Key to mastering number formatting: leading zeros and specific width

For generating number strings like order numbers that have leading zeros or a specific width, we need to understand some common format specifiers:

  1. Integer type (d): dThis is the type identifier used 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 thanx, will be filled.
  3. Leading zero fill (0):If the minimum width of the numberxis 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.

We assume that we want a number to always be displayed as 5 digits, and to be filled with zeros if it is less than 5 digits:

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

The output of the above code will be:00123.

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

If we do not add0it will be filled with spaces by default:

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

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

The actual application in the AnQi CMS template

Imagine that you are building an order details page for a website, and you need to display order numbers with a uniform format, or display product IDs with a fixed number of digits in a product list.stringformatit comes into play.

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

in the Aqy CMS, documents (archive) It usually 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.IdYes1The output would be:订单号:ORD-000001. Ifitem.IdYes12345The output would be:订单号:ORD-012345.

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

Scenario two: Formatting 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 %}

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

Combined with other template tags and variables

stringformatThe filter can be flexibly combined with other security CMS template tags and filters.You can format each item's ID within a loop, or 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

PassstringformatFilter, Safe 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 is to create a unified order number, product code, or any other number string that requires a fixed length and leading zero padding,stringformatCan always lend you a helping hand, making the website content more professional and standardized.

Common Questions and Answers (FAQ)

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

Q2: If the variable I want to format is not a numeric type but uses%dWhat will happen if I use such a numeric format symbol?A2:stringformatFilter internally tries to perform type conversion. If your variable is a string representation of a number (such as "123"), it usually converts to a number correctly and operates according to%dFormat. But if the variable is a completely non-numeric string (for example, "hello"), then using%dIt may result in output as0auto or an empty string, the specific behavior depends on the internal implementation. To ensure accuracy, it is best to confirm the type of the variable before formatting or use a more general%sformat specifier (string).

Q3: How to add a custom prefix to a formatted number string, such as 'ORD-' or 'SKU-'?A3: In the security CMS template, you can directly instringformatThe external string concatenation of the filter output result. 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 concatenated with the string 'ORD-'.