As an experienced website operations expert, I know that the use of templates is the core of the vitality of a flexible system like AnQiCMS.Especially when it comes to business logic such as price calculation and inventory management, ensure that it is executed accurately, which directly affects user experience and even the operational efficiency of the enterprise.Today, let's delve deeply into how to ensure that complex arithmetic logic such as addition, subtraction, multiplication, and division runs correctly and efficiently in AnQiCMS templates.

The template engine of Anqi CMS adopts syntax similar to Django, which is not only powerful but also encapsulates technical details well, making it easy for content operators to handle.When we talk about price calculation, it usually means that we need to retrieve data from the background, perform a series of calculations, and finally display the results clearly to the user.

Anqi CMS template's 'Calculator': Arithmetic Operation Tags

First, AnQiCMS templates are built-in with powerful arithmetic calculation capabilities, which is like having a calculator built into the template.You can directly use basic arithmetic symbols such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) in the template to perform calculations between numbers.

For example, if you need to calculate the final selling price of a product, it can be the base price, plus shipping, and then multiplied by a certain quantity. All these operations can be expressed intuitively in the template:

{# 假设 archive.Price 是商品单价,archive.ShippingCost 是运费,quantity 是购买数量 #}
{% set initialPrice = archive.Price|float %}
{% set shipping = archive.ShippingCost|float %}
{% set totalCost = (initialPrice + shipping) * quantity %}

You can even handle more complex expressions, specifying the order of operations with parentheses, just like you learned in math class:

{# 假设有一个复杂的折扣逻辑,先减去固定费用,再打折,然后加上增值税 #}
{% set basePrice = archive.OriginalPrice|float %}
{% set fixedDeduction = system.FixedDiscount|float|default:"0.0" %} {# 从系统设置中获取固定扣除额 #}
{% set discountRate = archive.DiscountRate|float|default:"1.0" %} {# 如果没有折扣率,默认为100% #}
{% set taxRate = 0.13 %} {# 13% 增值税 #}

{% set priceAfterDeduction = basePrice - fixedDeduction %}
{% set discountedPrice = priceAfterDeduction * discountRate %}
{% set finalPrice = discountedPrice * (1 + taxRate) %}

You can see that, whether it is simple addition or complex logic involving multiple steps and variables, the AnQiCMS template engine can directly complete the calculation through these arithmetic operators.

Where does the data come from? Obtain and prepare the data required for the calculation

The first step in making accurate calculations is to ensure that the data you have obtained is correct and exists in the correct format.

1. Retrieve data from the content model

In AnQiCMS, your product prices, inventory, and other data are usually stored in custom fields of content models (such as "product model"). For example, you may have defined a field namedPriceA numeric field to store the price, a field namedStockA numeric field to store inventory.

In the template, you can usearchiveDetailtag or inarchiveListIn the loop, directly access these fields:

{# 在产品详情页获取当前产品的价格和库存 #}
{% archiveDetail productData %}
  {% set productPrice = productData.Price %}
  {% set productStock = productData.Stock %}
{% endarchiveDetail %}

{# 或者在产品列表页遍历时获取 #}
{% archiveList products with moduleId="2" type="list" limit="10" %}
  {% for item in products %}
    {% set itemPrice = item.Price %}
    {% set itemStock = item.Stock %}
    {# 可以在这里对 itemPrice 和 itemStock 进行计算 #}
  {% endfor %}
{% endarchiveList %}

2. Ensure the data type is correct: Use type conversion filters cleverly

Data retrieved from the database, even if defined as a "numeric" type in the background, may be treated as a string when read in the template.Directly performing mathematical operations on strings can lead to unexpected results (for example, "10" + "5" results in "105" instead of "15").

To avoid this situation, AnQiCMS provides powerfulFilterHelp us with type conversion.floatandintegerThe filter is your powerful assistant:

  • |float: Convert the variable to a floating-point number.
  • |integer: Convert the variable to an integer.

Use it before any arithmetic operation, it is best to first use|floator|integerThe filter to transform variables:

{% set productPrice = productData.Price|float %} {# 确保价格是浮点数 #}
{% set quantity = system.DefaultQuantity|integer %} {# 确保数量是整数 #}

3. Handle missing values: gracefully face the situation of “no price”

Sometimes, a field may not be set or may be empty. Directly performing calculations on empty values can lead to errors or inaccurate results. AnQiCMS'sdefaultThe filter helps us set default values, making the calculation process more robust:

{# 如果 productData.Price 为空,则默认使用 0.0 #}
{% set productPrice = productData.Price|float|default:"0.0" %}
{# 如果 system.DefaultQuantity 为空,则默认使用 1 #}
{% set quantity = system.DefaultQuantity|integer|default:"1" %}

{# 这样即使原始数据缺失,计算也能顺利进行 #}
{% set calculatedTotal = productPrice * quantity %}

By chaining calls|float|default:"0.0"We first try to convert the data to a floating-point number, if the conversion fails or the data is empty, then use the default value0.0.

Build complex calculation logic: variable assignment and conditional judgment

In practice, price calculation is often not a simple linear formula. It may depend on multiple conditions and needs to be done in steps.

1. Variable assignment and intermediate results: making logic clearer.

AnQiCMS template insetLabels allow you to define and assign variables, which is very helpful for breaking down complex calculation processes and storing intermediate results:

"`twig {# Assume we have a logic to adjust discounts based on purchase quantity #} {% set baseItemPrice = item.Price|float|default:"0.0" %} {% set purchaseQuantity = 5 %} {# Assume the user buys 5 of them #}

{% set discountFactor = 1.0 %} {# Default no discount #} {% if purchaseQuantity