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

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" }}.