In AnQiCMS (AnQiCMS), using custom fields flexibly to manage various content, including product prices, service fees, and other numerical information is an important aspect for enhancing the personalization and functionality of the website.However, when using these price data, we often need to calculate or format it in a specific way, such as calculating the total price, applying discounts, or simply displaying it as currency with two decimal places.Ensure these operations are executed correctly, we need to pay attention to several key steps.
The basics of custom fields: choose 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 let the price data stored in a field participate in mathematical operations, be sure to select this field in the content model.“Number”Type, not the default “Text line”.
- Select “Number” typeIn the background, go to 'Content Management' under 'Content Model', select the model you need to edit (such as 'Product Model'), and then when adding or editing fields in 'Content Model Custom Fields', set the 'Field Type' to 'Number'.This ensures that AnQiCMS will store data in numeric format when storing data, thereby laying the foundation for subsequent calculations.
- Avoid storing price in “Text line”.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 that 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 design phase of custom fields is the first step to ensure that the price can be calculated correctly.
Get price data in the template.
Whether you are getting the built-in price field of AnQiCMS (such asarchive.Price) or a custom price field (such asproductPrice), you can use it in the templatearchiveDetailorarchiveParams.
- Get built-in price field:
{{ archive.Price }} - Retrieve a custom price field (for example named
actualPrice): If you create a custom field by directly using the field name (such asactualPrice), you can retrieve it like this:
Or, if you are using{% archiveDetail with name="actualPrice" %}archiveParamsLoop to retrieve, need to find the correspondingFieldNameitem:
at this point,{% archiveParams params %} {% for item in params %} {% if item.FieldName == "actualPrice" %} <div>实际价格:{{ item.Value }}</div> {% endif %} {% endfor %} {% endarchiveParams %}item.Valuewill include the price you entered.
Convert the price string to a computable number.
Even if you set the custom field to 'numeric' type in the background, or in some special cases, the price data is still in string format, we can use the filters provided by AnQiCMS to perform type conversion to ensure they can participate in calculations. Here, the main use isfloatandintegerfilter.
Prices usually contain decimals, thereforefloatThe filter will convert strings to floating-point numbers, which is more common when dealing with 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 enhance the robustness of the template and prevent errors when the price field is empty or contains 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 %}
So, even ifitem.ValueIt is empty,price_valueWill also be set securely to0.0To avoid calculation errors.
Perform price arithmetic operations
Once the price data is ensured to be of numeric type, we can make use of the arithmetic calculation capabilities of the AnQiCMS template to perform calculations. The AnQiCMS template supports direct mathematical expressions and can also useaddApply filters for more specific operations.
Basic arithmetic operations: You can use common operators such as addition (+), subtraction (-), multiplication (*), and division (/) in the template.
Assume you want to calculate the total price including tax, with a tax rate of 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: For simple addition operations,addthe filter also provides a convenient way.{% set base_price = 100.00 %} {% set shipping_cost = 10.50 %} {% set final_price = base_price|add:shipping_cost %}
Formatted price display
After calculating the final price, it is usually necessary to format it better for the user, such as retaining two decimal places and adding a currency symbol.floatformatandstringformatThe filter is very useful in this regard.
floatformatUsed to retain decimal places: If you need to converttotal_priceRetain two decimal places:{{ total_price|floatformat:2 }} {# 例如输出 226.00 #}floatformatThe filter can also intelligently handle numbers, such as{{ 226.00|floatformat }}It will output.226(without decimal),{{ 226.50|floatformat }}It will output.226.5(Round to one decimal place). When you need to strictly retain a certain number of decimal places, please enter the specific number.Combined with currency symbols and
stringformatTo add a currency symbol, you can directly concatenate strings in the template, or you can also make use ofstringformatto achieve more flexible formatting.{# 直接拼接 #} <span>总价:¥ {{ total_price|floatformat:2 }}</span> {# 使用 stringformat #} <span>总价:{{ total_price|stringformat:"¥ %.2f" }}</span>Here
%.2fRepresents formatting a floating-point number to two decimal places.
By following these steps, from creating custom fields, data retrieval, type conversion, to the final calculation and formatting, you can ensure the correct calculation and elegant display of custom price strings in Anqi CMS.
Frequently Asked Questions (FAQ)
Q1: Why am I entering numbers in custom fields, but when performing addition operations in the template, the result is string concatenation instead of numerical addition?
A1:This is likely because you set the 'field type' to 'single line text' instead of 'number' when creating custom fields in the background.Single-line text" type will treat any content you input as a string."}To solve this problem, it is recommended that you change the type of this custom field to 'number'.If the field type cannot be changed or for other reasons it is necessary to use "Single Line Text", then after obtaining the value of the field in the template, it is necessary to use|floator|integerThe filter explicitly converts it to a numeric type, for example{{ item.Value|float|add:other_value }}.
Q2: How can you ensure that the price is always displayed with two decimal places and a currency symbol in the template?
A2:You can usefloatformatorstringformatFilter to achieve this purpose.
- Use
floatformatManually add the currency symbol afterwards:<span>总价:¥ {{ total_price|floatformat:2 }}</span>. - Use
stringformatCan be done in one go:<span>总价:{{ total_price|stringformat:"¥ %.2f" }}</span>.%.2fSpecified to be formatted as a floating-point number and retain two decimal places.
Q3: If my price field may be empty or not filled in some documents, will it 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 ofdefaultSet a default safe value for the filter, for example0.0So when the price field actually has no value, it will be replaced with0.0to ensure the smooth operation of calculations. For example:{% set safe_price = archive.Price|float|default:0.0 %}.