How to use the `stringformat` filter to format price numbers as currency in Anqi CMS template (e.g., "¥%.2f")?

When displaying product or service prices on the website, we all hope that they look clear and professional, and are easy to understand.A string 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.stringformatFilter is a powerful tool that formats numbers into standard currency format.

This article will guide you on how to use the AnQi CMS template,stringformatFilter, easily convert price numbers into a more readable and professional currency format, such as the common "¥123.45" we see.


UnderstandingstringformatFilter: Make prices more 'decent'

The template engine of AnQi CMS supports template tags similar to Django syntax and provides a rich set of built-in filters to process data.stringformatFilters are like in the Go languagefmt.Sprintf()Function, which can convert any type of value (number, string, boolean, etc.) into a string according to the format you define.

For price numbers, we usually want:

  1. Display currency symbol:For example, the "¥" of the Chinese Yuan.
  2. Uniform decimal places:Most currencies are accustomed to retaining two decimal places, even if they are integers, they are displayed as.00.
  3. Round off:Ensure that the price display conforms to financial standards.

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

How to usestringformatFormat prices

UsestringformatThe basic syntax of the filter is very intuitive:

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

The key point is in the "format definition" part. For formatting numbers as currency in two decimal places (taking RMB as an example), you can define it like this:"¥%.2f".

Let's break down this '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, tellingstringformatA value should be inserted here.
  • .2: Represents keeping two decimal places for floating-point numbers. If the original number has more decimal places, it will be rounded automatically; if it has only one decimal place or no decimal places, it will be filled in.
  • f: Represents a variable to be formatted as a floating-point number (float).

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

Actual application scenarios in the AnQi CMS template

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

1. Product Details Page (archiveDetail)

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

{# 获取当前页面的产品详情,或者指定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)

In 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 a 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. Custom modules or tables

If you use custom content modules or tables to display data on the website, you can apply it as long as you can access the price variablestringformatFilter. For example, in a custom 'On Sale' 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%.2fOutside of this, you can also adjust according to your needs:

  • Only show integers:If you only want to display integer prices without decimals, you can use:stringformat:"¥%.0f"。For example123.45it will be displayed as¥123.
  • Without currency symbols but retaining decimals:If you only want to unify the decimal places but do not need the currency symbol, you can use it directlystringformat:"%.2f".
  • Other formats:Go languagefmt.Sprintf()All format definitions supported can be tried here. For example,%dfor integers,%sUsed for strings and others.

Summary

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


Common Questions (FAQ)

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

A1: WhenstringformatFilter receives a variable value that cannot be parsed as a number, it will usually try to process it as0or an empty value. To avoid displaying¥0.00or blank on the page, it is recommended to usestringformatbefore usingifCheck if a variable exists or is a valid number, or combinedefaultSet a default display text for the filter. 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 the US dollar$or 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 US dollar prices, you can use"$%.2f"If you want to display the euro price, you can use"€%.2f". The template engine of Anqi CMS 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.%.2fto%.0ffor example{{ item.Price|stringformat:"¥%.0f" }}Here, even if the original price has a decimal, it will be displayed in integer form after rounding. If a more strict integer display is required, it can also be used firstintegerFilter converts the price to an integer and then formats it, for example{{ item.Price|integer|stringformat:"¥%d" }}.