In website template development, we often need to perform some basic arithmetic operations, such as calculating the sum, adjusting values, or comparing values based on specific conditions.AnQiCMS (AnQiCMS) leverages its efficient architecture based on the Go language and its flexible template engine inspired by Django style, providing users with an intuitive and powerful way to perform arithmetic operations such as addition of numbers or strings in templates.

The template syntax design of Anqi CMS makes technical information presentable in an easily understandable manner in the template without complex backend code, enabling dynamic numerical processing directly on the frontend page.

Flexibly use arithmetic operation tags (calc)

When more complex arithmetic expression calculations, logical judgments, or numerical comparisons are needed, AnQi CMS provides a dedicatedarithmetic operation tagscalcThis tag allows you to directly write mathematical expressions in the template, whose results can be output directly or used for conditional judgments.

You can write mathematical formulas as you would for regular mathematics.{{ ... }}Operations such as addition, subtraction, multiplication, and division are performed within 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, are also applicable:

{{ (item.Price * item.Quantity) + ShippingCost }}

In addition to basic addition, subtraction, multiplication, and division,calcTags also support more advanced mathematical operations, such as modulo (%This is very useful in certain scenarios (such as determining odd or even lines or loop cycles).

In terms of logical judgment,calcThe expressiveness of the label is also very good. You can{% if ... %}Comparisons are made directly using the comparison operator (==,!=,<,>,<=,>=) 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 mapping usinginornot inOperators, which bring great flexibility to template logic.

{% if "VIP" in user.Roles %}
  <span>VIP专属内容</span>
{% endif %}

Convenient for addition:addFilter

For the need of just performing addition operations, Anqi CMS provides a more concise one.addFilter. This filter is specifically designed to add two values, whether they are numbers or strings. Its strength lies in its ability to intelligently handle different types of data.

UseaddWhen using a filter, you just need to place the variable you want to operate on after the pipe symbol|in front of the filter nameaddfollowed by a colon:then follow with 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 }}will output7. If one or both operands are strings,addthe filter will try to concatenate strings. For example,{{ "Hello " | add: "World" }}will output"Hello World". Even when numbers and strings are mixed, if they can be reasonably converted, they will be added together. Otherwise, they will be concatenated or kept as they are.

This flexible feature allowsaddThe filter is very convenient when it is needed to quickly combine strings or perform simple numerical addition, reducing the trouble of type conversion.

Data type and precision control: making calculations more accurate.

When performing arithmetic operations in the template, data types and precision are important aspects to pay attention to.Although AnQi CMS template engine has certain intelligence in handling type conversion, sometimes we may need to perform explicit type conversion to ensure the accuracy of the calculation result.

integerandfloatFilterWhen you retrieve data from the database, which is by default of string type, and you need to perform numerical operations on it, you can use these two filters to force the conversion to integer or float.

{{ "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 adding thousand separators, padding leading zeros, etc., you can usestringformatfilter, which is similar to the one in Go language,SprintfFunctions provide powerful formatting capabilities.

{{ "总金额: %.2f 元" | stringformat:total_amount }} {# 格式化输出带两位小数的金额 #}

With these filters, you can ensure that arithmetic operations in the template are not only executed correctly but also displayed in a user-friendly format.

Application scenarios in practice

The arithmetic operation function in Anqi CMS template is widely used in daily website operations:

  • Product display pageCalculate and display the product discount price, shipping fee, tax, and final total.
  • Member system:According to the user's points or level, different preferential amounts are displayed, or the rewards obtained by the user are calculated.
  • Content statistics:Display the growth of article reading volume, comment count statistics, and even simple year-on-year and month-on-month calculations.
  • List page interaction: Adjust the style or display hints of list items dynamically based on inventory quantity, user ratings, and other numerical values.
  • Countdown featureCalculate the remaining time until an event (such as the end of an activity, order deadline) occurs.

Summary

The AnQi CMS template engine provides great convenience to website operators and template developers with 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.Mastering these features will enable you to build smarter and more efficient websites within the Anqi CMS framework.


Frequently Asked Questions (FAQ)

Q1: Can I directly perform arithmetic operations like addition, subtraction, multiplication, and division in the statement?{% if ... %}Can I perform arithmetic operations like addition, subtraction, multiplication, and division in the statement?A1: It's okay. The AnQi CMS template engine supports using{% if ... %}arithmetic operations, comparison operators (==,!=,<,>,<=,>=), and logical operators (and,or,notPerform arithmetic and logical judgments. For example{% if item.Price * item.Quantity > 100 %}Is perfectly valid.

Q2: If my variable is of string type but actually represents a number, can I perform addition operations directly?A2: For addition, you can useaddFilter. For example, ifvariableIs"10",{{ variable | add: 5 }}It will output15It tries to intelligently convert strings to numbers. But for other operations (such as multiplication or division), or to ensure type strictly, it is recommended to use first.integerorfloatThe filter explicitly converts it to a numeric type, for example{{ variable | integer * 5 }}.

Q3: How can I ensure that my number is always displayed in a specific format in the template, such as two decimal places?A3: You can usefloatformatA filter to control the number of decimal places for floating-point numbers, for example{{ total_amount | floatformat:2 }}Willtotal_amountFormat to two decimal places. For more general string formatting, such as adding currency symbols or percentages,stringformatThe filter provides powerfulSprintfformatting capabilities of style.