In website template development, we often need to perform some basic arithmetic operations on the data, such as calculating the sum, adjusting the values, or comparing the values based on specific conditions.AnQiCMS (AnQiCMS) offers an intuitive and powerful way to perform arithmetic operations such as addition of numbers or strings in templates, thanks to its efficient architecture based on the Go language and its flexible template engine inspired by the Django style.
The template syntax design of Anqi CMS makes it possible to present technical information in a way that is easy to understand within the template. Dynamic numerical processing can be directly implemented on the front-end page without complex backend code.
灵活运用算术运算标签 (English)calc)
当需要进行更复杂的算术表达式计算、逻辑判断或数值比较时,安企CMS提供了一个专用的 (English)算术运算标签 (English)calcThis tag allows you to write mathematical expressions directly in the template, and the result can be output directly or used for conditional judgments.
You can write mathematical expressions just like you would write conventional mathematical formulas, in{{ ... }}Perform addition, subtraction, multiplication, division, and other operations inside double curly braces. For example, if there is a variable nameditem.Pricerepresenting the price of the product, and anotheritem.Quantityrepresenting the quantity, then the total price can be calculated as follows:
{{ item.Price * item.Quantity }}
More complex expressions, such as those containing parentheses to control the order of operations, also apply:
{{ (item.Price * item.Quantity) + ShippingCost }}
In addition to basic addition, subtraction, multiplication, and division,calcLabels also support more advanced mathematical operations, such as modulo (%This is very useful in certain scenarios (such as determining odd or even rows or cycles).
In terms of logical judgment,calcthe expressiveness of the label is also excellent. You can{% if ... %}The statement uses comparison operators directly ()==,!=,<,>,<=,>=) to compare numbers:
{% if item.Stock <= 5 %}
<span style="color: red;">库存紧张,仅剩 {{ item.Stock }} 件!</span>
{% endif %}
You can even check if a value exists in a list or a map, usinginornot inOperator, which brings great flexibility to the template logic.
{% if "VIP" in user.Roles %}
<span>VIP专属内容</span>
{% endif %}
For addition: convenient.addFilter
For the need to perform addition only, Anqi CMS provides a simpler solution.addFilterThis filter is specifically designed to add two values together, whether they are numbers or strings. Its strength lies in its ability to intelligently handle different types of data.
UseaddFiltering, just place the variable you want to operate on after the pipe symbol|before the filter nameaddfollowed by a colon:, then the value you want to add:
{{ initial_value | add: value_to_add }}
If both operands are numbers, they will be added directly, for example,{{ 5 | add: 2 }}it will output:7.
If one or both operands are strings,addthe filter will try to concatenate strings. For example,{{ "Hello " | add: "World" }}it will output:"Hello World"Even if it is a mix of numbers and strings, if it can be reasonably converted, addition will be performed; otherwise, it will attempt to concatenate or retain the original value.
This flexible feature makesaddFilter is very convenient when it is necessary to quickly combine strings or perform simple numerical summation, reducing the trouble of type conversion.
Data type and precision control: Make calculations more accurate.
When performing arithmetic operations in templates, data type and precision are important aspects to consider.Although the template engine of Anqie CMS has a certain degree of intelligence in handling type conversion, there are times when we may need to explicitly perform type conversion to ensure the accuracy of the calculation results.
integerandfloatFilterWhen the data you retrieve from the database is of default string type and you need to perform numerical operations on it, you can use these two filters to force convert it to an integer or a floating-point number.
{{ "10" | integer | add: 5 }} {# 将字符串“10”转换为整数10,然后加5,输出15 #}
{{ "3.14" | float | add: 1.0 }} {# 将字符串“3.14”转换为浮点数3.14,然后加1.0,输出4.14 #}
floatformatFilterFor floating-point arithmetic results, you may need to control the number of decimal places displayed to avoid overly long decimals or unnecessary precision.floatformatThe filter can help you achieve this:
{{ total_price | floatformat:2 }} {# 将 total_price 保留两位小数输出 #}
stringformatFilter:If you need more fine-grained output format control, such as comma-separated thousands, leading zero padding, etc., you can usestringformatfilters, which are similar to the ones in Go language,SprintfFunction, provides powerful formatting capabilities.
{{ "总金额: %.2f 元" | stringformat:total_amount }} {# 格式化输出带两位小数的金额 #}
Through these filters, you can ensure that arithmetic operations in the template are not only executed correctly but also displayed in a user-friendly format.
Actual application scenarios
The arithmetic operation feature in the Anqi CMS template is widely used in daily website operations:
- Product display pageCalculate and display the discount price, shipping fee, tax, and final total price of the product.
- Member system:Display different discounts based on user points or levels, or calculate the rewards obtained by the user.
- Content statistics:Dynamic display of the growth of the number of articles read, the number of comments statistics, and even simple year-on-year and month-on-month calculations.
- List page interactionBased on inventory quantity, user ratings, and other numerical values, dynamically adjust the list item style or display prompt information.
- Countdown functionCalculate the remaining time to an event (such as the end of an activity, order deadline).
Summary
The template engine of Anqi CMS provides great convenience for website operators and template developers through its built-in arithmetic operation tags and a series of practical filters.Whether it is a simple addition of numbers or complex logical judgments and numerical formatting, it can be easily realized at the template level, greatly enhancing the dynamicity and interactivity of content display.Master these features, and you will be able to build smarter and more efficient websites under the framework of AnQi CMS.
Common Questions (FAQ)
Q1: Can I directly perform arithmetic operations like addition, subtraction, multiplication, and division in the statement?{% if ... %}Can I directly perform arithmetic operations like addition, subtraction, multiplication, and division in the statement?A1: It's okay. The template engine of AnQi CMS supports direct use of arithmetic operations, comparison operators ({% if ... %}and logical operators (==,!=,<,>,<=,>=) as well.and,or,notPerforming arithmetic and logical operations. For example{% if item.Price * item.Quantity > 100 %}It is completely legal.
Q2: If my variable is of string type but actually represents a number, can I perform addition directly?A2: For addition, you can useaddFilter. For example, ifvariableYes"10",{{ variable | add: 5 }}it will output15Because it will attempt to smartly convert strings to numbers. But for other operations (such as multiplication or division), or to ensure the type more strictly, it is recommended that you use first.integerorfloatThe filter explicitly converts it to a numeric type, for example{{ variable | integer * 5 }}.
Q3: How can I ensure that my numbers are always displayed in a specific format in the template, such as two decimal places?A3: You can usefloatformatFilter to control the number of decimal places of floating-point numbers, for example,{{ total_amount | floatformat:2 }}will betotal_amountformatted to two decimal places. For more general string formatting, for example, adding a currency symbol or percentage,stringformatthe filter provides powerfulSprintfformatting capabilities of style.