How to use the `stringformat` filter in Anqi CMS template to format price numbers as currency (such as “¥%.2f”)?

Calendar 👁️ 69

When displaying product or service prices on a website, we all want them to look clear and professional, at a glance.A sequence of price numbers without currency symbols and inconsistent decimal places, which not only affects the appearance but may also raise doubts about the professionalism of the product.Fortunately, AnQiCMS (AnQiCMS) powerful template engine provides a variety of practical filters, includingstringformatThe filter is a tool that formats numbers into standard currency format.

This article will guide you on how to use the Anqi CMS template to,stringformatFilter, easily converts price numbers into more readable and professional currency formats, such as the common "¥123.45".


UnderstandingstringformatFilter: Make the price more 'respectable'

The AnQi CMS template engine supports template tags similar to Django syntax, providing a rich set of built-in filters to process data.stringformatFilters are like in Go language.fmt.Sprintf()A function that can convert any type of value (number, string, boolean, etc.) into a string in the format you define.

For price numbers, we usually want:

  1. Display currency symbol:For example, the RMB symbol “¥”.
  2. Uniform decimal places:Most currencies are used to retain two decimal places, even if they are integers, also displayed as:.00.
  3. Rounding:Ensure that the price display complies with financial standards.

stringformatThe filter can perfectly meet these requirements, making your website's price display more standardized and professional.

How to usestringformatFormat price

UsestringformatThe basic syntax of the filter is very intuitive:

{{ 你的价格变量 | stringformat:"格式定义" }}

The key here lies in the 'format definition' section. For formatting numbers into currency form with two decimal places (for example, in RMB), you can define it like this:"¥%.2f".

Let's break down the 'format definition':

  • ¥ : This is the currency symbol you want to display before the number. You can replace it as needed.$/etc.
  • %: This is the beginning of a placeholder, tellsstringformatHere is the value to be inserted.
  • .2It indicates that the decimal (fraction) is retained to two places. If the original number has more decimal places, it will be rounded off automatically; if it has only one or no decimal places, it will be filled in.
  • f: Indicates that the variable to be formatted is a floating-point number (float).

So, if your product price variable isitem.Priceand its value is123.456Then use:{{ item.Price|stringformat:"¥%.2f" }}the result will be¥123.46If the price is100The output will be¥100.00isn't it instantly standardized?

In the actual application scenarios of Anqi CMS templates

The Anqi CMS flexible content model means that price data may appear in different places,stringformatFilters can handle it easily.

1. Product detail page (archiveDetail)

On the product details page, we usually display detailed information about a single product, including its price. Assuming your product model has a field namedPricethe field:

{# 获取当前页面的产品详情,或者指定ID的产品详情 #}
{% archiveDetail archiveItem with name="Price" %}
    <p><strong>产品价格:</strong> {{ archiveItem|stringformat:"¥%.2f" }}</p>
{% endarchiveDetail %}

{# 如果你直接在详情页模板中访问当前文档的属性,可以直接使用 archive.Price #}
<p><strong>产品价格:</strong> {{ archive.Price|stringformat:"¥%.2f" }}</p>

2. Product list page (archiveList)

On the product list page, you need to iterate through multiple products and display their thumbnails and prices:

{% archiveList products with moduleId="2" type="page" limit="8" %}
    {% for product in products %}
    <div class="product-card">
        <h3><a href="{{ product.Link }}">{{ product.Title }}</a></h3>
        <img src="{{ product.Thumb }}" alt="{{ product.Title }}">
        <p class="product-price">售价: {{ product.Price|stringformat:"¥%.2f" }}</p>
        {# 假设产品还有一个自定义字段叫做 original_price 用于显示原价 #}
        {% if product.original_price %}
        <p class="original-price">原价: <del>{{ product.original_price|stringformat:"¥%.2f" }}</del></p>
        {% endif %}
    </div>
    {% empty %}
    <p>暂无产品可供展示。</p>
    {% endfor %}
{% endarchiveList %}

Here we assumeoriginal_priceIs an additional custom field added to the product model. In the Anqi CMS backend content model, you can easily define these additional fields and set their types.

3. In a custom module or table

If you use a custom content module or table to display data on your website, you can apply it as long as you can get the price variable.stringformatFilter. For example, in a custom 'special offer' list:

{% set special_offer_price = 88.80 %}
<p>今日特价商品:仅售 {{ special_offer_price|stringformat:"¥%.2f" }}!</p>

Tip: Make the format more flexible

stringformatThe strength of the filter lies in the flexibility of its 'format definition.' Besides%.2fIn addition, you can adjust as needed:

  • Only show integers:If you only want to show integer prices without decimals, you can use:stringformat:"¥%.0f"For example:123.45It will be displayed as¥123.
  • Without currency symbols but keep decimals:If you only want to standardize the number of decimal places but do not need the currency symbol, you can use it directlystringformat:"%.2f".
  • Other formats:Go languagefmt.Sprintf()All supported format definitions can be tried here. For example,%dUsed for integers,%sfor strings and such.

Summary

BystringformatFilter, Anqi CMS allows website operators to easily format prices professionally and uniformly in templates.This not only enhances the visual effect of the website content, but also improves the user experience, making the display of your product and service prices clearer and standardized.Master this skill, and your website content operation will soar to new heights.


Frequently Asked Questions (FAQ)

Q1: If my price variable is empty or not a number,stringformatHow will the filter handle?

A1: WhenstringformatWhen the filter receives a variable value that cannot be parsed as a number, it usually tries to process it as0or empty. To avoid displaying on the page¥0.00or blank, it is recommended to usestringformatfirst, useifa statement to check if a variable exists or is a valid number, or combinedefaultFilter sets a default display text. For example:{{ item.Price|default:0|stringformat:"¥%.2f" }}, so ifitem.Priceis empty, it will display¥0.00.

Q2: Besides the Chinese Yuan symbol¥, can I use US dollars$Or do you want other currency symbols?

A2: Of course you can. You just need to replace the currency symbol in the "Format Definition". For example, if you want to display the price in US dollars, you can use"$%.2f"; If you want to display the euro price, you can use"€%.2f". Anqi CMS template engine will output the string you provide directly.

Q3: I only want to display integer prices without decimals, how should I format it?

A3: If you only need to display integer prices, you can set it in the format definition.%.2fchanged to%.0fFor example{{ item.Price|stringformat:"¥%.0f" }}. Even if the original price has decimals, it will be rounded to display as an integer. If a stricter integer display is required, it can also be used first.integerThe filter converts the price to an integer and then formats it, for example{{ item.Price|integer|stringformat:"¥%d" }}.

Related articles

How to configure the separator (`sep`) and whether to display the parent category title (`showParent`) for the `tdk` filter in Anqin CMS?

During website operations and SEO optimization, the page title (Title) is a key element to attract user clicks and improve search engine rankings.AnQiCMS provides a flexible `tdk` filter, allowing us to finely control the display of page TDK (Title, Description, Keywords).Among these parameters, `sep` and `showParent` play a crucial role in building page titles with rich hierarchy and clarity.

2025-11-08

How to concatenate the article title (Title) with the system-defined website name (SiteName) through the `tdk` filter and output it to the <title> tag in the Anqi CMS template?

In website operation, the importance of the `<title>` tag is self-evident. It is not only the key for search engines to understand the theme of the page, but also the content that users see first in the search results.A well-crafted page title that can effectively increase click-through rates and have a positive impact on SEO optimization.Therefore, how to organically integrate the core title of the article with the brand name of the website to form an accurate and attractive `<title>` tag is a fundamental and important link in the design of website templates.AnQiCMS as a feature-rich enterprise-level content management system

2025-11-08

The `dump` filter has what practices in debugging Anqi CMS templates, and how to clearly view the structure and value of complex variables?

During the template development process of AnQi CMS, we often encounter the need to view variable content and structure, especially when dealing with complex objects passed from the background.If you cannot clearly know what is inside the variable, debugging will be as difficult as a blind man feeling an elephant.The AnqiCMS adopts the Pongo2 template engine syntax similar to Django, providing rich tags and filters to help us build dynamic pages, one extremely powerful debugging tool is the `dump` filter.### `dump` filter

2025-11-08

How to safely output HTML code passed from the backend in Anqi CMS template using the `safe` filter without escaping?

Build and manage websites in AnQi CMS, we often make good use of its powerful and flexible template system to present colorful content.The template engine of AnQi CMS has adopted the syntax of Django templates, which brings us a familiar development experience and powerful features.However, when handling HTML code passed from the backend to the frontend, we encounter an important security mechanism: **automatic escaping**.

2025-11-08

How does the `stringformat` filter handle null or invalid input in AnQi CMS, will it return an error or a default value?

In Anqi CMS template design, we often encounter scenarios where we need to format variable output.At this point, the `stringformat` filter is particularly important, as it helps us clearly display numbers, strings, and even other types of data according to the format we preset.However, when using such tools, a common and crucial question is: how will `stringformat` handle it when the variable itself is null or invalid?Is it a direct error that causes the page to crash, or is there a more elegant default behavior?

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

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

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