In AnQiCMS, flexibly using custom fields to manage various content, including product prices, service fees, and other numerical information, is an important aspect for enhancing the website's personalization and functionality.However, when using these price data, we often need to calculate or format them in a specific way, such as calculating the total price, applying discounts, or simply displaying them as currency with two decimal places.To ensure that these operations are executed correctly, we need to pay attention to several key steps.
The basics of custom fields: choosing the correct data type
Firstly, everything starts with the settings you make when creating custom fields in the AnQi CMS backend. When you intend to allow the price data stored in a field to participate in mathematical operations, be sure to select this field in the content model.“Number”Type, not the default “Single-line text”.
- Select the “Number” type:In the background, go to “Content Management” under “Content Model”, select the model you need to edit (for example, “Product Model”), and then set the “Field Type” to “Number” when adding or editing fields in “Content Model Custom Fields”.So, AnQiCMS will ensure that the data is in numeric format when storing it, thus laying the foundation for subsequent calculations.
- Avoid storing prices in “Single-line text”If the price is stored as 'single-line text', even if you enter pure numbers, the system will treat it as a string.This means, performing direct addition, subtraction, multiplication, or division operations on it may not yield the expected results and may even cause errors.
So, planning in the custom field design stage is the first step to ensure that the price is calculated correctly.
Get price data in the template
No matter whether you are getting the price field built-in in AnQiCMS (such asarchive.Price) or a custom price field (such asproductPrice), you can use it in the templatearchiveDetailorarchiveParamsLabel.
- Get built-in price field:
{{ archive.Price }} - Get custom price field (for example named)
actualPrice): If you create a custom field by its name (such as)actualPrice),you can access it like this:
Or, if you are using{% archiveDetail with name="actualPrice" %}archiveParamsLoop to get, need to find the correspondingFieldNameitem:
At this time,{% archiveParams params %} {% for item in params %} {% if item.FieldName == "actualPrice" %} <div>实际价格:{{ item.Value }}</div> {% endif %} {% endfor %} {% endarchiveParams %}item.ValueIt will include the price you entered.
Convert the price string to a computable number
Even if you set the custom field to 'number' type in the background or in some special cases where the price data still appears as a string, we can use the filters provided by AnQiCMS to perform type conversion, ensuring that they can participate in calculations. This mainly involvesfloatandintegerFilter.
The price usually includes decimals, sofloatThe filter will convert strings to floating-point numbers, which is more commonly used when handling currency. If your prices are always integers, you can useinteger.
For example,item.Valueis a string representation of the price "99.99", usingfloatFilter conversion:
{% set price_value = item.Value|float %}
To improve the robustness of the template, prevent errors caused by the price field being empty or containing non-numeric characters, we can combinedefaultFilter, set a default value for it (usually 0 or 0.0):
{% set price_value = item.Value|float|default:0.0 %}
In this way, even though item.ValueThe content inside the loop will not be rendered, instead, the content of the block will be displayed.price_valuewill also be set safely:0.0To avoid calculation errors.
Perform arithmetic operations on prices
Once the price data is ensured to be of numeric type, we can make use of the arithmetic capabilities of the AnQiCMS template for calculations. The AnQiCMS template supports direct mathematical expressions and can also useaddFilters for more specific operations.
Basic arithmetic operationsYou can use common operators such as addition (+), subtraction (-), multiplication (*), and division (/) in the template.
假设您想计算包含税费的总价,税率为13%:
{% set unit_price = archive.Price|float|default:0.0 %} {% set quantity = 2 %} {# 假设数量为2件 %} {% set subtotal = unit_price * quantity %} {% set tax_rate = 0.13 %} {% set tax_amount = subtotal * tax_rate %} {% set total_price = subtotal + tax_amount %}Use
addFilter:对于简单的加法运算,add过滤器也提供了便捷的方式。{% set base_price = 100.00 %} {% set shipping_cost = 10.50 %} {% set final_price = base_price|add:shipping_cost %}
格式化价格显示
After calculating the final price, it is usually necessary to format it to better present it to the user, such as retaining two decimal places and adding a currency symbol.floatformatandstringformatThe filter is very practical in this aspect.
floatformat用于保留小数位数: 如果您需要将total_price保留两位小数:{{ total_price|floatformat:2 }} {# 例如输出 226.00 #}floatformat过滤器还可以智能地处理数字,例如{{ 226.00|floatformat }}It will output226(不带小数),{{ 226.50|floatformat }}It will output226.5(Keep one decimal place). When it is necessary to strictly keep a certain number of decimal places, please enter the specific number.Combined with the currency symbol and
stringformatTo add a currency symbol, you can directly concatenate strings in the template or usestringformatto achieve more flexible formatting.{# 直接拼接 #} <span>总价:¥ {{ total_price|floatformat:2 }}</span> {# 使用 stringformat #} <span>总价:{{ total_price|stringformat:"¥ %.2f" }}</span>Here
%.2fThe value indicates formatting a floating-point number to two decimal places.
Through these steps, from the creation of custom fields, data acquisition, type conversion, to the final calculation and formatting, you can ensure the correct calculation and elegant display of custom price strings in the Safe CMS.
Common Questions (FAQ)
Q1: Why is the result of the addition operation in the template a string concatenation instead of numeric addition when I enter a number in the custom field?
A1:This is likely because you set the 'Field Type' to 'Single Line Text' instead of 'Number' when creating a custom field in the background.“Single-line text” type treats any content you enter as a string.To solve this problem, it is recommended that you change the type of this custom field to 'numeric'.|floator|integerThe filter explicitly converts it to a numeric type, for example{{ item.Value|float|add:other_value }}.
Q2: How to ensure that the price is always displayed with two decimal places and prefixed with a currency symbol in the template?
A2:You can usefloatformatorstringformatFilter to achieve this purpose.
- Use
floatformatManually add the currency symbol after.<span>总价:¥ {{ total_price|floatformat:2 }}</span>. - Use
stringformatCan be done all at once:<span>总价:{{ total_price|stringformat:"¥ %.2f" }}</span>. Among them%.2fSpecified to be formatted as a floating-point number and retain two decimal places.
Q3: If my price field may be empty or unfilled in some documents, will this cause the template to error? How should I handle it?
A3:Yes, if the price field is empty or contains non-numeric content, directly performing the calculation may cause the template to error. To avoid this situation, you can combine the use ofdefaultFilter sets a default security value for it, for example0.0. Thus, when the price field actually has no value, it will be replaced with0.0, ensuring the smooth progress of calculations. For example:{% set safe_price = archive.Price|float|default:0.0 %}.