During the operation of a website, we often encounter scenarios where we need to perform calculations on custom data, such as dynamically calculating prices based on product parameters, displaying rating statistics, or performing other numerical processing based on user input or content attributes.AnQi CMS provides us with the ability to meet these requirements with its flexible content model and powerful template engine.This article will give a detailed introduction on how to perform numerical calculations based on user-defined string parameters in Anqi CMS.
Step 1: Preparation - Define your custom parameters
Firstly, we need to define the fields to store these parameters in the background. The "Content Model" feature of Anqi CMS is the core of achieving this.
- Enter content model management:Log in to the AnQi CMS backend, find 'Content Management' in the left navigation bar, and click to enter 'Content Model'.
- Edit or create a new model:You can choose to edit an existing content model (such as 'article model' or 'product model'), or create a custom model as needed.
- Add custom field:In the model editing page, find the 'Content Model Custom Field' area, click 'Add Field'.
- Parameter name:Fill in the Chinese name you want to display and recognize in the background (for example, "Product Price", "Stock Quantity").
- Call field:Fill in the English field name used for reference in the template (for example,
price/stockThis field name is crucial, please ensure its uniqueness and standardization. - Field type:Although we will eventually perform numerical calculations, considering the diversity of user input, we recommend that you select the field type as 'number'.This helps to perform preliminary data validation during input in the background, ensuring that the user enters numbers, reducing the complexity of subsequent processing.
- Other settings:Set whether required, default value, etc. according to actual needs.
- Save and Apply:Save your model changes.
After completing these steps, when publishing or editing content belonging to this content model, you will be able to see these custom fields in the "Other Parameters" area and enter the corresponding values.
The second step: Retrieve the custom parameter value in the template
Define the parameters and fill in the content, and then the next step is to obtain and use these parameters in the website front-end template. Anqi CMS provides multiple ways to obtain custom parameters.
Get the value of a single custom parameter
If you know which specific custom field you want to get (for exampleprice), you can use it directlyarchiveDetailTags:
{# 假设当前页面是商品详情页,并有一个名为 'price' 的自定义字段 #}
<div>商品价格:{% archiveDetail with name="price" %} 元</div>
{# 如果自定义字段的值需要赋值给一个变量,以便后续计算使用 #}
{% archiveDetail productPrice with name="price" %}
<div>商品价格(通过变量):{{ productPrice }} 元</div>
HereproductPriceit is the temporary variable name we specify for this custom field.
Get all custom parameters and iterate over them
If you need to get all the custom parameters of the current content or you want to dynamically display them, you can usearchiveParamsLabel. This label will return an array object containing all custom parameters:
{# 获取当前内容的所有自定义参数,并命名为 params #}
{% archiveParams params %}
<div class="custom-params">
{% for item in params %}
<div>
<span>{{ item.Name }}:</span>
<span>{{ item.Value }}</span>
</div>
{% endfor %}
</div>
{% endarchiveParams %}
In this case,item.NameIt will display the "parameter name" (Chinese) you set in the background,item.ValueThen it will display the actual value of the parameter.
The third step: Perform numerical calculation - core step
After obtaining the value of the custom parameter in the template, we can make use of the arithmetic calculation ability of the AnQi CMS template engine to perform calculations. Here is a key point to note:Type conversion.
Understanding the importance of type conversion
Even if you set the custom field to 'numeric' type in the background, the template engine of Anqi CMS may still read it as a string in some cases.Directly performing mathematical operations on strings can lead to errors or unexpected results (for example, "10" + "5" might become "105" instead of "15").Therefore, before performing numerical calculations, we strongly recommend using a filter to explicitly convert these values to numeric type.
Using filters for type conversion
AnQi CMS providesintegerandfloatTwo filters are used for type conversion:
integer: Convert the value to an integer. If the value contains a decimal, it will be rounded down. If the value cannot be converted to a number, it will return0.floatConvert the value to a floating-point number (a decimal number). If the value cannot be converted to a number, it returns0.0.
The method of conversion is very simple, just apply the filter to your parameter variable:
{% archiveDetail productPriceString with name="price" %} {# 获取到的值可能是字符串 "100.50" #}
{% set productPrice = productPriceString | float %} {# 转换为浮点数 100.50 #}
{% archiveDetail productStockString with name="stock" %} {# 获取到的值可能是字符串 "5" #}
{% set productStock = productStockString | integer %} {# 转换为整数 5 #}
Perform arithmetic operations
The AnQi CMS template engine supports basic arithmetic operators, you can use them directly in double curly braces{{ }}inside, just like in a programming language:
+: Addition-: Subtraction*Multiplication/Division%Modulus (remainder)^Power operation (exponentiation)
Combine the number converted to type with the operator to perform calculation:
{# 假设我们已经通过 archiveDetail 获取了 price 和 stock 并转换为了数字类型 #}
{% archiveDetail priceString with name="price" %}
{% set price = priceString | float %}
{% archiveDetail stockString with name="stock" %}
{% set stock = stockString | integer %}
{% set totalValue = price * stock %} {# 计算总价值 #}
<div>商品总价值:{{ totalValue }} 元</div>
To make the code clearer and more readable, especially when calculations involve multiple steps, you can use{% set %}tags to define temporary variables to store intermediate results.
Complete calculation example: Calculate the discounted price of a product
Assuming we have a product, in addition to the pricepriceThere is also a custom fielddiscount_rateUsed to represent the discount rate (for example0.8represents an 80% discount).
Define field:Add in the product model
priceAnd (numeric type) anddiscount_rate(numeric type) field.Template code:
{# 获取商品价格 #} {% archiveDetail priceString with name="price" %} {% set price = priceString | float %} {# 获取折扣率 #} {% archiveDetail discountRateString with name="discount_rate" %} {% set discountRate = discountRateString | float %} {# 执行计算 #} {% set finalPrice = price * discountRate %} <div> <p>原价:{{ price }} 元</p> <p>折扣率:{{ discountRate }}</p> <p>折后价:{{ finalPrice | floatformat:2 }} 元</p> {# 使用 floatformat:2 保留两位小数 #} </div>
In this way, you can flexibly display various calculation results on the front-end based on the customized parameters of the backend.
Tip
- Data validation and default values:If the custom parameter may be empty or contain non-numeric characters, directly