As an experienced website operation expert, I know that the use of templates is the core of a website's vitality in a flexible system like AnQiCMS.Especially when it comes to business logic such as price calculation, inventory management, and so on, ensuring its accurate and error-free execution is directly related to user experience and even the operational efficiency of the enterprise.Today, let's delve into how to ensure that complex arithmetic logic such as addition, subtraction, multiplication, and division can run correctly and efficiently in the AnQiCMS template.

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

Anqi CMS template "calculator": arithmetic operation tags

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

For example, if you need to calculate the final selling price of a product, it could be the base price, plus shipping fees, 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) %}

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

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

The first step in making accurate calculations is to ensure that the data you obtain 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 namedPriceThe "numeric" type field is used to store prices, a field namedStockThe "numeric" type field is used to store inventory.

In the template, you can access these fields througharchiveDetaillabels orarchiveListthe loop:

{# 在产品详情页获取当前产品的价格和库存 #}
{% 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 data type correct: Use type conversion filter

Data retrieved from the database, even if defined as "numeric" in the background, may be treated as a string when read in the template.Performing mathematical operations directly on strings can result in unexpected outcomes (for example, "10" + "5" results in "105" rather than "15").

To avoid this situation, AnQiCMS provides powerfulFilterto help us with type conversion.floatandintegerFilter is your powerful assistant:

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

It is best to use it first before any arithmetic operation,|floator|integerFilter converts variables:

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

3. Handling Missing Values: Gracefully Dealing with 'No Price' Situations

Sometimes, a field may not be set or may be empty. If you calculate the empty value directly, it may lead to errors or inaccurate results. AnQiCMS'sdefaultThe filter helps us set default values to make 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 %}

Through chained 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, use the default value0.0.

Build complex calculation logic: variable assignment and conditional judgment

In practical applications, price calculation is often not a simple linear formula. It may depend on multiple conditions and needs to be done step by step.

1. Variable assignment and intermediate results: make the logic clearer.

AnQiCMS template'ssetTags allow you to define and assign variables, which is very helpful for decomposing complex calculation processes and storing intermediate results:

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