How to perform initial arithmetic operations on user input data in AnQi CMS template?

Calendar 👁️ 63

In AnQiCMS template design, performing preliminary arithmetic operations on user input data is a key link in achieving dynamic content display and interactive logic.AnQiCMS's powerful template engine, drawing on the characteristics of Go language and Django templates, provides developers with flexible and easy-to-understand arithmetic calculation capabilities, allowing you to handle various numerical logic in front-end templates without writing complex backend code.

Core arithmetic operations in the template

AnQiCMS template supports direct use within double curly braces{{ }}Perform basic arithmetic operations.Whether it is simple addition, subtraction, multiplication, and division, or a slightly more complex modulo operation, it can be completed directly here.This greatly simplifies data processing at the template level.

You can directly use common mathematical operators:

  • Addition(+)
  • Subtraction(-)
  • Multiplication(*)
  • Division(/)
  • Modulo(%)
  • Power operation(^)

For example, if you have a product with a template variablearchive.PriceRepresents the price,archive.StockIndicates the inventory quantity, to calculate the total inventory value, you can write it directly:

产品的总库存价值:{{ archive.Price * archive.Stock }} 元

A more complex expression, such as calculating the price of a product after a 70% discount and adding a fixed shipping fee:

打折后含运费价格:{{ archive.Price * 0.7 + 10 }} 元

Even priority operations within parentheses can be performed, for example, calculating the remainder of a number divided by 2:

{{ (archive.Stock + 7) % 7 }}

These operations support integers and floating-point numbers, the template engine will automatically handle data type conversion, making your calculation process smoother.

Use filters for auxiliary calculation and processing.

In addition to direct operators, AnQiCMS template filters also provide great convenience for data processing, especially in data type conversion and formatted output.

  1. addFilter: General Addition addThe filter can not only perform addition of numbers but also handle string concatenation.It will automatically try to convert the parameter to a number for addition, and if it fails, it will perform string concatenation.item.Quantityanditem.BonusQuantity) Add:

    总数量:{{ item.Quantity | add: item.BonusQuantity }}
    

    If a field's value is a string,addThe filter can also handle flexibly:

    文本和数字拼接:{{ "库存总量:" | add: archive.Stock }}
    
  2. integerandfloatFilter: Data Type ConversionData read from the database or data entered by the user in the background, which is sometimes stored as a string type. It is very important to ensure that they are numeric types before performing arithmetic operations.integerandfloatThe filter can convert a string to an integer or a floating-point number. For example, ifarchive.DiscountRatestored as “0.8” (a string), and you want to calculate the discounted price:

    当前折扣价格:{{ archive.Price * (archive.DiscountRate | float) }}
    

    Ifarchive.CountIt could be “5”, make sure it is an integer:

    乘以五:{{ (archive.Count | integer) * 5 }}
    
  3. stringformatFilter: formatted outputWhen displaying calculation results, especially when involving amounts or percentages, precise formatting is often required.stringformatThe filter can help you output numbers according to the formatting rules of the Go language. For example, keep the total price calculated to two decimal places:

    总计金额:{{ total_price | stringformat:"%.2f" }}
    
  4. divisiblebyFilter: Check for divisibilityThis filter can determine whether a number can be divided by another number and return a boolean value. It is often used in loops, such as implementing alternating row color effects:

    {% if forloop.Counter | divisibleby:2 %}
        <li class="even-row">...</li>
    {% else %}
        <li class="odd-row">...</li>
    {% endif %}
    

Combine variable assignment with logical control

To make the calculation process clearer, or if the calculation result needs to be used in multiple places later, we can combine{% set %}labels to define temporary variables. At the same time,{% if %}Tags can execute different logic based on the calculation results.

Assuming you need to judge whether the total price of the goods meets the free shipping condition:

{% set subtotal_price = archive.Price * archive.Quantity %}
{% set shipping_cost = 15 %} {# 假设固定运费 #}

{% if subtotal_price >= 200 %}
    {% set final_price = subtotal_price %}
    <p>恭喜您,订单满200元,免运费!</p>
{% else %}
    {% set final_price = subtotal_price | add: shipping_cost %}
    <p>订单未满200元,需支付运费:{{ shipping_cost }} 元。</p>
{% endif %}

<p>订单总计:{{ final_price | stringformat:"%.2f" }} 元</p>

This example demonstrates how to retrieve data, perform arithmetic calculations, store results in variables, and make conditional judgments based on variable values, ultimately outputting formatted results.

Summary

The arithmetic operation function in AnQiCMS templates, combined with its flexible filters and variable assignment mechanism, provides strong support for the dynamic processing of front-end content.Whether it is a simple numerical calculation or logical judgment based on the calculation result, it can be efficiently completed at the template level.This makes it easier to create a website that dynamically displays prices, quantities, discounts, or shows different content based on numerical conditions.


Frequently Asked Questions (FAQ)

  1. Ask: Can arithmetic operations be performed directly on numeric data stored as strings (e.g., “100”)?Answer: It is not recommended to perform arithmetic operations directly. Although in some cases the template engine may try to automatically convert, it is strongly recommended to useintegerThe filter converts it to an integer or usesfloatThe filter converts it to a floating-point number and then performs calculations. For example:{{ "100" | integer * 5 }}.

  2. Ask: Is AnQiCMS template layer suitable for handling very complex mathematical calculations?Answer: AnQiCMS template layer is mainly used for preliminary, display-level arithmetic operations and logical judgments.For scenarios involving a large amount of data processing, complex business rules, or high-precision calculations, we recommend placing this logic in the Go language backend and then passing the final result to the template for display.This helps maintain the clarity, maintainability, and ensure the performance and accuracy of the calculation.

  3. Ask: How can you store a calculation result in a template for reuse in multiple places?Answer: You can use{% set %}tags to define a temporary variable, and assign the calculation result to it. For example:{% set total_amount = item.Price * item.Quantity %}. Thistotal_amountThe variable can be used in the subsequent part of the current template

Related articles

How to get the friend link in Anqi CMS template and set the nofollow attribute?

In website operation, friendship links are an important means to enhance website authority and obtain external traffic.However, not all friendship links should pass on weight. It is particularly important to use the `rel="nofollow"` attribute reasonably to better manage the SEO performance of the website.The `nofollow` attribute tells search engines not to pass ranking weight from the current page to the target page, which is very useful when linking to non-core content, advertising pages, or third-party websites that cannot be fully trusted, and can effectively avoid SEO risks caused by low-quality links

2025-11-08

How to get the website name in Anqi CMS template and correctly concatenate it in the SEO title?

In website operation, a well-constructed SEO title is crucial for attracting user clicks and improving search engine rankings.It must not only accurately summarize the page content but also ingeniously integrate the brand information.For AnQiCMS users, how to dynamically obtain the website name in the template and correctly concatenate it into the SEO title is a practical and efficient skill.AnQiCMS as a content management system that focuses on SEO optimization, provides very flexible tags at the template level, allowing you to easily achieve this goal.

2025-11-08

How to get the category description with a specified ID in Anqi CMS template and truncate it?

In the Anqi CMS template, effectively managing and displaying category descriptions is a common requirement.Especially when displayed on list pages or block displays, we often need to show a concise introduction of the category rather than a full-length description.This article will provide a detailed introduction on how to obtain the specified ID category description in Anqi CMS template and perform appropriate truncation processing to ensure that the content is both concise and beautiful.Get category description by specified ID In AnQi CMS template, getting category details mainly depends on the `categoryDetail` tag

2025-11-08

How to remove leading or trailing non-visible characters from the string data obtained from the content acquisition module in the template?

When using AnQi CMS for website content operations, the content collection module is undoubtedly an important way to obtain a large amount of information and quickly enrich the website content.However, text data collected or imported from external sources often contains unnecessary leading or trailing spaces, newline characters, or even other invisible characters.These seemingly minor 'dirty data' can affect the aesthetics of page layout, content alignment, and even cause subtle negative impacts on search engine optimization (SEO).

2025-11-08

How to use if/else condition judgment to control content display in Anqi CMS template?

In AnQi CMS template creation, flexibly controlling the display of content is the key to improving website user experience and management efficiency.Whether it is to display specific information based on different conditions, or to implement more complex personalized layouts, conditional judgment is an indispensable tool.Today, we will delve into how to use the powerful `if/else` conditional judgment in Anqi CMS templates to accurately control the presentation of content. The template engine of AnQi CMS adopts syntax similar to Django template syntax, which allows web developers familiar with web development to quickly get started. Among them

2025-11-08

How to use a for loop to traverse an array and handle an empty array in Anqi CMS template

During the template development process of AnQi CMS, dynamic data display is one of the core requirements.No matter whether it is an article list, product display, or navigation menu, we cannot do without traversing array or collection data.How to elegantly handle empty data in this process, ensuring the beauty of the page and user experience is equally important.The AnQi CMS template engine supports powerful features similar to Django template syntax, among which the `for` loop is a powerful tool for handling data lists.

2025-11-08

How can I customize the content display layout of the AnQi CMS website?

The layout of website content display is a key factor in attracting visitors, enhancing user experience, and optimizing search engine rankings.A clear, beautiful, and functional layout that can make your website stand out among competitors.AnQiCMS (AnQiCMS) is an efficient content management system that provides high flexibility, allowing you to customize the display of website content according to your actual needs.This article will deeply explore how to customize the content display layout of the Anqi CMS website, helping you turn your creativity into reality and create a website with a unique style.--- ###

2025-11-08

What are the conventions for naming and storing AnQi CMS template files?

When you start using Anqi CMS to build a website, understanding the naming rules and storage path conventions of its template files is the key to efficient website design and content presentation.A clear file structure can not only help you quickly locate and modify templates, but also make team collaboration smoother, ensuring stable operation of the website. ### The "home" of template files: unified storage location All template files of AnQi CMS are stored centrally in the `/template` folder under the project root directory.This is like a large library, where all books (template topics) are collected here

2025-11-08