During the operation of the 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.AutoCMS offers the ability to meet these requirements with its flexible content model and powerful template engine.This article will introduce in detail how to perform numerical calculations based on the user-defined string parameters in the 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 the Anqi CMS is the core to achieve this.

  1. Enter the content model management:Log in to the security CMS backend, find 'Content Management' in the left navigation bar, and click to enter 'Content Model'.
  2. 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.
  3. Add custom fields:In the model editing page, find the "Content Model Custom Fields
    • Parameter name:Fill in the Chinese name (e.g., 'Product Price', 'Stock Quantity') that you want to display and recognize in the background.
    • Field call:Fill in the English field name used to reference in the template (e.g., price/stock)。This field name is crucial, please ensure its uniqueness and standardization.
    • Field Type:Although we will ultimately perform numerical calculations, considering the diversity of user input, we recommend you select the field type as 'number'.This helps to perform initial data validation during background input, ensuring that the user enters numbers and reduces the complexity of subsequent processing.
    • Other settings:Set whether it is required, default value, etc. according to actual needs.
  4. Save and apply:Save your model changes.

After completing these steps, when publishing or editing content belonging to this content model, you can see these custom fields in the "Other Parameters" area and enter the corresponding values.

第二步:In the template, obtain the value of the custom parameter

After defining the parameters and filling in the content, the next step is to obtain and use these parameters in the website front-end template. Anqi CMS provides multiple methods for obtaining custom parameters.

Get the value of a single custom parameter

If you know the specific custom field you want to get (for exampleprice), you can use it directly,archiveDetailTags:

{# 假设当前页面是商品详情页,并有一个名为 'price' 的自定义字段 #}
<div>商品价格:{% archiveDetail with name="price" %} 元</div>
{# 如果自定义字段的值需要赋值给一个变量,以便后续计算使用 #}
{% archiveDetail productPrice with name="price" %}
<div>商品价格(通过变量):{{ productPrice }} 元</div>

Here are theproductPricewhich 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 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 backgrounditem.ValueIt will display the actual value of the parameter.

Third step: Perform numerical calculation - core step

After obtaining the value of the custom parameter in the template, we can use the arithmetic calculation capability of the Anqi CMS template engine to perform calculations. Here is a key point to note:Type conversion.

The importance of understanding type conversion

Even if you set the custom field to 'number' 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 for type conversion:

  • integerConvert the value to an integer. If the value contains a decimal, it will be truncated down. If the value cannot be converted to a number, it will return0.
  • floatConvert the value to a floating-point number (a number with decimals). If the value cannot be converted to a number, it returns0.0.

The conversion method is 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 template engine of Aiqi CMS supports basic arithmetic operators, you can use them directly in double curly braces{{ }}as you would 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 %}labels to define temporary variables for storing intermediate results.

Complete calculation example: Calculate the discounted price of the product

Suppose we have a product, in addition to the pricepriceThere is also a custom fielddiscount_rateUsed to represent the discount rate (for example0.8Represents 20% off).

  1. Define field:Add in the product model:price(numeric type) anddiscount_rate(numeric type) field.

  2. 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>
    

By this means, you can flexibly display various calculation results on the front end based on the customized parameters from the backend.

Tips

  • Data validation and default values:If the custom parameter may be empty or contain non-numeric characters,