In website operations, we often need to dynamically display some numeric information, such as the total price of products, the percentage of article reading, the discounted price, and so on.The template system provided by AnqiCMS is powerful, it uses a syntax similar to Django template engine, allowing us to easily meet these requirements in content display, perform basic arithmetic operations directly in the template, and display the results.

Master basic arithmetic operations in the template

In the Anqi CMS template, the most direct way is to write arithmetic expressions in double curly braces{{ }}This is very similar to the calculator function we use in daily life, supporting addition+, subtraction-Multiplication*Division/as well as modulus (remainder)%and basic operations.

Imagine that you might want to display the result of adding two numbers on a page, or calculate a percentage of a number. These operations can be performed directly in the template, for example:

{# 简单的加法 #}
<p>25 + 10 的结果是: {{ 25 + 10 }}</p>

{# 减法运算 #}
<p>50 - 15 的结果是: {{ 50 - 15 }}</p>

{# 乘法运算 #}
<p>5 * 8 的结果是: {{ 5 * 8 }}</p>

{# 除法运算,这里会得到浮点数结果 #}
<p>10 除以 3 的结果是: {{ 10 / 3 }}</p>

{# 整数除法,会得到整数部分 #}
<p>10 整除 3 的结果是: {{ 10 // 3 }}</p>

{# 取模运算,得到余数 #}
<p>10 除以 3 的余数是: {{ 10 % 3 }}</p>

In actual display,{{ 10 / 3 }}It will output.3.3333333333333335while{{ 10 // 3 }}it will output3This means that when performing division, if you want to get an exact floating-point result, you usually use/and if you only need the integer part, you can use//Or through subsequent filters to be processed.

These expressions can also include parentheses to clarify the order of operations, just like you learned in math class. For example, calculate(5 + 3) * 2The result is:

<p>(5 + 3) * 2 的结果是: {{ (5 + 3) * 2 }}</p>

Integrate website data into arithmetic operations

The mere operation of fixed numbers is often not enough to meet our needs, the charm of a website lies in the dynamism of its content.AnQi CMS allows us to retrieve various data from the background and use the numeric values in the template calculations.

Assuming we have a product details page, the unit price of the product isarchive.Price(Through the document details tagarchiveDetailGet the field, and we want to calculate the total price of buying 3 items. We can do this:

{# 假设 archive.Price 是一个数字,比如 29.99 #}
{% archiveDetail productPrice with name="Price" %}
<p>商品单价:¥{{ productPrice }}</p>
<p>购买 3 件商品的总价:¥{{ productPrice * 3 }}</p>

Or if your document model has a custom numeric field, such asStock(Inventory), if you want to display how much inventory is left in percentage, you can calculate it like this:

{# 假设 archive.TotalStock 是一个固定值,archive.CurrentStock 是当前库存 #}
{% archiveDetail totalStockValue with name="TotalStock" %}
{% archiveDetail currentStockValue with name="CurrentStock" %}

{% if totalStockValue > 0 %}
  {% set remainingPercentage = (currentStockValue / totalStockValue) * 100 %}
  <p>总库存:{{ totalStockValue }}</p>
  <p>当前库存:{{ currentStockValue }}</p>
  <p>库存剩余百分比:{{ remainingPercentage|floatformat:2 }}%</p> {# 使用 floatformat 过滤器保留两位小数 #}
{% else %}
  <p>库存信息不可用或总库存为零。</p>
{% endif %}

Here we introduced one{% set %}tag to define a temporary variableremainingPercentageand usedfloatformat:2a filter to keep the result to two decimal places, making the display more tidy.

Using the filter for more flexible calculations

The AnQi CMS template system also provides some practical filters (Filters) that can help us process and calculate data. Filters are added by adding a vertical bar after the variable name.|And use the filter name.

Among them,addThe filter is very suitable for performing simple addition operations. It can not only be used for adding numbers, but also cleverly handle the mixed addition of numbers and strings (if possible, it will try to convert the types, otherwise, it will ignore the parts that cannot be converted).

{# 使用 add 过滤器进行加法 #}
<p>5 加 2 的结果是: {{ 5|add:2 }}</p>

{# 变量与数字相加 #}
{% set baseNum = 10 %}
<p>10 加 7 的结果是: {{ baseNum|add:7 }}</p>

{# 字符串与数字相加(会尝试拼接,如“安企” + 2 = “安企2”) #}
<p>“安企”与 2 相加: {{ "安企"|add:2 }}</p>

Sometimes, the value obtained from the custom field at the back may be treated as a string.In this case, performing arithmetic operations directly may result in errors or unexpected results.To ensure the accuracy of the calculation, we can useintegerorfloatThe filter explicitly converts the value to an integer or floating-point number:

{# 假设 custom_price_str 是一个字符串“25.50” #}
{% archiveDetail customPriceStr with name="custom_price" %}
<p>字符串价格乘以 2: {{ customPriceStr|float * 2 }}</p> {# 先转换为浮点数再乘 #}

Practical tips and suggestions

  • Variable assignment ({% set %}or{% with %}):When we need to perform more complex calculations, or when we want to store intermediate results for later use,{% set %}and{% with %}Tags are very useful. They can help you organize code and make logic clearer.{% set newVar = someCalculation %}Used to define variables within the current scope, while{% with %}is usually used to temporarily define a group of variables and{% endwith %}end.
  • Combine conditional judgment:Combine conditional judgment{% if %}Tags can make our dynamic display more intelligent. For example, it will only be displayed when the calculation result is positive, or display different prompts according to the different ranges of the results.
  • Note the data type:Although the Anq CMS template engine sometimes tries to automatically convert data types, it is explicitly usedintegerorfloatA filter to ensure that the data involved in the calculation is of the correct numeric type is a good habit, which can avoid potential errors.
  • Handle special cases:When performing division, be especially aware of the case where the denominator is zero. Although the underlying Go language of Anqie CMS usually handles it gracefully, to improve user experience, you can add conditional judgments in the template to avoid directly displaying the result of division by zero, for example{% if totalStockValue > 0 %}.

By flexibly using the above arithmetic operation functions and filters, you can realize rich dynamic number display in the Anqi CMS template, greatly enhancing the interactivity and practicality of website content.


Frequently Asked Questions (FAQ)

1. Why do the numbers concatenate instead of adding when I perform addition operations on them in the template?

This is usually because the 'number' involved in the operation has been identified as a string by the template engine. When a string performs addition