In AnQiCMS, templates are the cornerstone of displaying website content.Flexible use of templates not only makes the content display more colorful and diverse, but also enables dynamic effects through some built-in functions.Among them, performing arithmetic operations directly in the template is a very practical feature that many users may overlook.It allows us to process numbers directly in the front-end template without writing additional backend code, performing operations such as addition, subtraction, multiplication, and division, thus achieving more dynamic display effects or logical judgments.
AnQiCMS's template system borrows the syntax of Django template engine, which makes it highly flexible and intuitive in handling variables, logical controls, and arithmetic operations.Below, we will discuss in detail how to perform these arithmetic operations directly in the AnQiCMS template.
1. Basic arithmetic operations
In AnQiCMS template, you can use addition (+), subtraction (-), multiplication (*), division (/) as well as modulo (%)operator. These operators can be directly applied to variables or constants of numeric type.
Addition (
+)and subtraction(-)They are the most basic operations, used for addition or subtraction.{{ 10 + 5 }} {# 输出 15 #} {{ 20 - 7 }} {# 输出 13 #} {% set itemPrice = 100 %} {% set discount = 15 %} 商品的最终价格是:{{ itemPrice - discount }} {# 输出 85 #}Multiplication (
*) and division (/)Used to calculate the product or quotient. It should be noted that the results of integer division and floating-point division may differ.{{ 4 * 6 }} {# 输出 24 #} {{ 10 / 3 }} {# 如果两个操作数都是整数,结果可能被截断为整数,输出 3 #} {{ 10 / 3.0 }} {# 至少一个操作数是浮点数时,结果会保留小数,输出 3.333333 #} {% set viewCount = 500 %} {% set factor = 0.1 %} 阅读量得分:{{ viewCount * factor }} {# 输出 50.0 #}To ensure that the result of floating-point division is obtained, it is recommended to explicitly write one of the operands as a floating-point number (for example
3.0), or use the modulus operation mentioned laterfloatFilter performs type conversion.(}
%)Modulus operation returns the remainder of division of two numbers, which is often used in templates to implement scenarios such as alternating styles of list items (odd and even rows).{{ 10 % 3 }} {# 输出 1 #} {% for item in archiveList %} <div class="item-{% if forloop.Counter % 2 == 0 %}even{% else %}odd{% endif %}"> {# ... 内容 ... #} </div> {% endfor %}
Second, composite expressions and precedence
When you need to mix multiple operations in an expression, you can use parentheses()to clarify the order of operations. As with the rules in mathematics, operations within parentheses are executed first.
{{ (10 + 5) * 2 }} {# 先计算 10+5=15,再乘以2,输出 30 #}
{{ 10 + 5 * 2 }} {# 先计算 5*2=10,再加10,输出 20 #}
{% set basePrice = 50 %}
{% set taxRate = 0.1 %}
{% set shippingCost = 5 %}
总价:{{ basePrice * (1 + taxRate) + shippingCost }} {# 输出 50 * 1.1 + 5 = 55 + 5 = 60 #}
三、Comparison and Logical Operations
AnQiCMS template supports comparison operators and logical operators in addition to arithmetic operations, which are very useful for conditional judgments.
Comparison operatorsUsed to compare the size or equality of two values, returns a boolean.
trueorfalse).- Equal to:
== - Not equal to:
!= - Less than:
< - Greater than:
> - Less than or equal to:
<= - Greater than or equal to:
>=
{% set currentNum = 10 %} {% if currentNum > 5 %} 数字大于5 {% endif %} {% if currentNum == 10 %} 数字等于10 {% endif %}- Equal to:
Logical operatorsUsed to combine multiple conditions, returns a boolean.
- And:
and(or)&&) - Or:
or(or)||) - Not:
not(or)!)
{% set isVip = true %} {% set userLevel = 3 %} {% if isVip and userLevel > 2 %} 高级VIP用户 {% endif %} {% if not isVip or userLevel < 1 %} 非VIP或低等级用户 {% endif %}- And:
Member operator (
in/not in)Check if a value exists in a list, array, or dictionary (map/struct), or if a key exists in a dictionary.{% set colorList = ["red", "green", "blue"] %} {% if "red" in colorList %} 列表中包含红色 {% endif %} {% set productTags = {"new": true, "sale": false} %} {% if "new" in productTags %} {# 检查键是否存在 #} 新品标签存在 {% endif %}
English, combining actual data for calculation
The most powerful place of arithmetic operations lies in the ability to process dynamic data obtained from the built-in tags of AnQiCMS.For example, you may need to calculate a 'hotness' score based on the article's page views or perform a currency conversion based on product prices.
{# 假设 archive.Views 是文章的浏览量,archive.Id 是文章ID #}
{% set hotScore = archive.Views * 0.05 + archive.Id * 0.01 %}
<p>文章热度得分:{{ hotScore }}</p>
{# 假设 product.Price 是产品价格,需要显示加税后的价格 #}
{% set productPrice = product.Price %}
{% set taxRate = 0.08 %} {# 8%的税率 #}
<p>含税价格:{{ productPrice * (1 + taxRate) }}</p>
{# 假设有一个自定义字段 item.stock 表示库存,当库存低于10时显示“库存紧张” #}
{% if item.stock <= 10 and item.stock > 0 %}
<span style="color: orange;">库存紧张!剩余 {{ item.stock }} 件</span>
{% elif item.stock == 0 %}
<span style="color: red;">已售罄</span>
{% else %}
<span>库存充足</span>
{% endif %}
Through the above examples, we can see that performing arithmetic and logical operations directly in the AnQiCMS template can greatly enhance the expression capabilities and dynamics of the template, reduce dependency on backend logic, and make the front-end page more flexible and intelligent.
Practical Tips
- Keep it simple:Although the template supports complex calculations, it is recommended to keep the logic in the template as simple as possible. Complex calculations and business logic are still more suitable for handling on the backend.
- Note the data type:When performing operations that may involve decimals, such as division, ensure that at least one operand is a floating-point number to avoid precision loss caused by integer division. AnQiCMS also provides
floatandintegerFilter, can explicitly perform type conversion, for example{{ some_var|float * 0.1 }}. - Sufficient testing:Any calculation performed in the template, especially in a production environment, should be thoroughly tested to ensure the results meet expectations and to avoid user experience issues caused by calculation errors.
Common Questions (FAQ)
1. Can I directly use the variable obtained through AnQiCMS tag in arithmetic operations?Yes, it can be done completely. For example, if you go through{% archiveDetail with name="Views" %}Get the article's page views, you can assign it to a variable and then use it directly in an expression:{% set views = archive.Views %}{{ views * 0.5 }}.