Direct expression calculation in the template
AnQiCMS的模板引擎支持在双大括号{{ }}Internally, it performs various mathematical and arithmetic operations, which is very similar to many modern template languages such as Django, Blade, etc.You can use common operators in programming languages to perform operations such as addition, subtraction, multiplication, and division on numbers and variables.
下面我们来看看一些常用的算术运算和它们的用法:
1. 加法 (+)When you need to add two numbers, you can simply use the plus sign. For example, if you have a product priceitem.Priceand a taxtax, and you want to display the final price including tax:
{{ item.Price + tax }}
Or, if you want to calculate the sum of two variables:
{{ quantity + bonus }}
2. Subtraction (-)Subtraction operations are also intuitive. For example, calculate the discounted price:
{{ originalPrice - discountAmount }}
Or display the remaining stock:
{{ totalStock - soldAmount }}
3. Multiplication (*)Multiplication is often used to calculate total prices or ratios. For example, to calculate the cumulative price of multiple items:
{{ item.Price * item.Quantity }}
Or to calculate a percentage:
{{ totalSales * 0.15 }} {# 计算15%的销售额 #}
4. Division (/)Division can be used to calculate an average or distribute proportions. For example, to calculate average visits:
{{ totalViews / numberOfPosts }}
It should be noted that if the divisor is zero, the system will usually report an error or return a special value, so in practical applications, you may need to use conditional judgment to avoid such situations.
5. Modulo (%)Modulus operation returns the remainder of the division of two numbers. This is very useful for determining odd or even numbers, or for implementing alternating styles in loops. For example, to determine whether a product ID is even:
{% if item.Id % 2 == 0 %}
<div class="even-item">{{ item.Title }}</div>
{% else %}
<div class="odd-item">{{ item.Title }}</div>
{% endif %}
Hereitem.Id % 2it will return0(ifitem.Idis even)or1(ifitem.Idis odd),then with0compare.
6. Comparison operationIn addition to direct arithmetic operations, you can also perform comparisons between numbers in the template, which is very common in conditional judgments. Common comparison operators include:
- 等于 (
==) - Not equal (
!=) - 小于 (
<) - Greater than (
>) - 小于等于 (
<=) - 大于等于 (
>=)
These comparison operators are often used with:{% if %}Label combination usage:
{% if product.Stock <= 5 %}
<span style="color: red;">库存紧张!</span>
{% endif %}
{% if user.Level >= 3 %}
<p>恭喜您成为VIP用户!</p>
{% endif %}
7. Logical OperationsLogical operators allow you to combine multiple conditions. Common logical operators include:
- AND (
andor&&) - Or (
oror||) - Not (
notor!)
For example, check if a product is in stock and the price is within a specific range:
{% if product.Stock > 0 and product.Price < 100 %}
<p>这是一个热门的实惠商品!</p>
{% endif %}
{% if user.IsAdmin or user.IsEditor %}
<p>您有权限编辑此内容。</p>
{% endif %}
{% if not article.IsPublished %}
<p>本文仍在草稿箱中。</p>
{% endif %}
Use variables for calculations:Variables defined in the template can directly participate in calculations, for example fromarchiveDetailLabel gets the document details of the tag,systemLabel gets system settings, etc.
{% archiveDetail productPrice with name="Price" %}
{% system shippingCost with name="ShippingCost" %}
<p>商品总价 (含运费):{{ productPrice + shippingCost }} 元</p>
Make sure the variables you get are of numeric type; otherwise, it may lead to inaccurate calculation results.
Use a filter for calculations
AnQiCMS's template engine also provides a series of filters that can perform various transformations and processing on variables, including some related to numerical operations.
1.addFilter
addThe filter is specifically used for executing addition operations and is very convenient in chained operations.
{{ number|add:5 }} {# 将 number 的值加上 5 #}
This filter can be used not only for numbers but also for string concatenation.
{{ "Hello "|add:"World!" }} {# 输出 "Hello World!" #}
2.divisiblebyFilterThis filter can check if a number can be divided by another number without a remainder, and returns a boolean value.
{% if productId|divisibleby:3 %}
<p>这是第三组的商品。</p>
{% endif %}
3. Type conversion filter (integer,float)Sometimes the values from the database or external input may be of string type, but you need to perform mathematical operations on them.integerandfloatThe filter can convert these strings to their corresponding numeric types.
{{ "100"|integer + 20 }} {# 结果为 120 #}
{{ "3.14"|float * 2 }} {# 结果为 6.28 #}
If the conversion fails, they will return0or0.0.
4.stringformatFilterAfter completing the calculation, you may need to format the result into a specific string format, such as retaining two decimal places.stringformatThe filter can achieve this, it is similar toprintffunction.
{{ (totalAmount * 1.05)|stringformat:"%.2f" }} {# 计算含5%税的总额并保留两位小数 #}
Examples of practical scenarios
Suppose you are building a product list page and you want to display the serial number of each product,