In website operations, we often need to dynamically display some numeric information, such as the total product price, percentage of article reading, discounted price, etc.The template system provided by Anqi CMS is powerful, it uses a syntax similar to the Django template engine, allowing us to easily implement these requirements when displaying content. We can perform basic arithmetic operations on numbers 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 within double curly braces{{ }}In it, which is very similar to the calculator function we use in daily life, supporting addition+and subtraction-and multiplication*and division/as well as modulo (remainder) operation.%These basic operations.

Imagine that you might want to display the sum of two numbers on a page, or calculate what percentage a number represents. 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>

When displayed actually,{{ 10 / 3 }}It will output3.3333333333333335while{{ 10 // 3 }}it will output3. This means that when performing division, if you want to get an exact floating-point result,/[en]it will be; if only the integer part is needed, it can be used//or processed through subsequent filters.

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:

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

integrate website data into arithmetic operations

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

Assume we have a product detail page, the unit price of the product isarchive.Price(Through the document details tagarchiveDetailRetrieve the field), and we would like to calculate the total price of purchasing 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 percentage of inventory is left, 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 introduce one{% set %}a label to define a temporary variableremainingPercentageand usedfloatformat:2a filter to keep the result with two decimal places, making the display cleaner.

Utilize the filter for more flexible operations

The template system of Anqi CMS also provides some practical filters (Filters) that can help us process and calculate data. Filters are added by appending a vertical bar to the variable name.|Use it with the filter name.

Among them,addThe filter is very suitable for simple addition operations.It can not only be used for adding numbers, but also cleverly handle the addition of mixed 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 values obtained from custom fields in the background may be treated as strings.In this case, performing arithmetic operations directly may result in errors or unexpected outcomes.integerorfloatThe filter explicitly converts the value to an integer or a 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 %}The tag is very useful. It helps organize code and make logic clearer.{% set newVar = someCalculation %}Used to define variables within the current scope.{% with %}It is usually used to define a group of variables temporarily.{% endwith %}End.
  • Combine condition judgment:Combine condition judgment:{% if %}Tags can make our dynamic display more intelligent. For example, it only displays when the calculation result is positive, or shows different prompts based on different ranges of the result.
  • Note the data type:Even though the template engine of AnQi CMS tries to automatically convert data types in some cases, 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 operations, be particularly careful of the case where the denominator is zero. Although the underlying Go language of Anqi CMS can usually handle it gracefully, for the sake of 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 achieve rich dynamic digital display in the Anqi CMS template, greatly enhancing the interactivity and practicality of website content.


Common Questions (FAQ)

1. Why does the addition operation on numbers in the template result in the concatenation of two numbers instead of their sum?

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