How can I perform numerical calculations based on a user-defined parameter (string)?

Calendar 👁️ 48

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.

  1. 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'.
  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 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.
  4. 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).

  1. Define field:Add in the product modelpriceAnd (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>
    

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

Related articles

How to display product prices in AnQiCMS templates and control decimal places?

In website operation, the display of product prices is a crucial link, not only to ensure the accuracy of information, but also to ensure that the presentation method conforms to the reading habits and brand image of users.AnQiCMS with its flexible template system, provides users with powerful customization capabilities, allowing you to easily control the display of product prices, including decimal places.### How to get product price: Where does it come from? In the AnQiCMS template, the product price is usually stored and called as a field of the document (Article or Product)

2025-11-08

Which formatting placeholders does the `stringformat` filter support?

In AnQiCMS template development, in order to better display and control the presentation of data on the page, we often need to format variables.Among them, the `stringformat` filter is a very practical tool that allows us to convert numbers, strings, or other types of values into a specific string format according to predefined rules.The strength of this filter lies in its adoption of the placeholder syntax of the Go language `fmt.Sprintf()` function, making the control of output format flexible and accurate

2025-11-08

How to format numbers, strings, and any other values to output as strings in a specific format (`stringformat`)?

In the display of website content, we often need to present different types of data (such as numbers, strings, and even more complex structures) in a unified and precise manner on the page.The template engine of AnQiCMS provides powerful tools, one of which is a very practical feature called `stringformat` filter, which can help us format any value into a string of a specific format.When we retrieve data from the backend, whether it is the number of views of an article, the price of a product, or user-defined parameters, they may be represented by numbers

2025-11-08

What will the `get_digit` filter return if the position it accesses does not exist?

In AnQi CMS template development, flexibly using various filters (filters) can greatly enhance the efficiency and accuracy of content display.`get_digit` filter is one of the practical tools used to process numeric data.It allows us to extract a specific digit from a number accurately.However, a common issue during usage is: What will the `get_digit` filter return if the position being accessed exceeds the length of the number itself?### `get_digit`

2025-11-08

How can I convert a string price from a custom field into a number that can be used in the order total in the template?

In website operation, we often encounter the need to handle numerical data such as product prices or service charges.This data is sometimes stored in custom fields, but for various reasons, they may be saved in the form of strings (text), such as "199.50 yuan" or "150".When we need to perform a total calculation on these prices in a template (such as the order total), directly performing a 'sum' operation on the string will yield unexpected results (such as '199.5015.00' instead of '214.50').At this point, it is necessary to convert these string prices into actual numbers

2025-11-08

How to dynamically adjust the decimal precision of displayed numbers in a template?

In website content operation, the precise display of numbers is often crucial, whether it is product prices, statistical data, or technical indicators, the accuracy of decimal point display directly affects the accuracy of information and the understanding of users.AnQiCMS provides a flexible template engine that allows us to easily adjust the decimal precision of numbers in frontend templates, thus satisfying various complex display requirements.The AnQiCMS template system is developed based on Go language, with a syntax style similar to Django, it offers powerful Filter (Filter) functions

2025-11-08

How does `floatformat` prevent the display of the decimal part when a floating-point number is exactly an integer (such as 10.00)?

In website content operation, we often encounter situations where we need to display numbers.These numbers may come from a floating-point type in a database, but in some cases, when they are exactly integers (such as `10.00`, `50.0`), we want them to be presented in a more concise integer form, such as `10` or `50`, rather than with unnecessary decimal parts.AnQiCMS (AnQiCMS) provides powerful template tags and filters, where the `floatformat` filter is a powerful tool to solve such problems

2025-11-08

How to perform complex mathematical expression calculations in templates, such as exponentiation or multi-step operations?

In website content management, we often need to handle various data, and this data is not always in its final form.Sometimes, we need to perform simple addition, subtraction, multiplication, and division in templates, and sometimes even more complex mathematical operations, such as calculating squares, cubes, or handling complex expressions with multiple steps.For AnQiCMS users, the good news is that its template engine provides very flexible and powerful mathematical calculation capabilities, allowing us to easily meet these needs.The template system of AnQiCMS is based on Django template engine syntax

2025-11-08