In website operation, we often encounter the need to dynamically adjust the display content of the page based on data.For example, a product page needs to display "sufficient stock", "tight stock" or "temporarily out of stock" based on the inventory quantity;A user points page may display 'Regular Member', 'Senior Member', or 'VIP Member' based on the level of points.The powerful template engine of Anqi CMS provides a flexible way to implement these functions, especially by combining cleverlystringformatFilters andif.

This article will delve into how to use these two tools in Anqi CMS templates to make your website content more intelligent and user-friendly.

stringformatFilter: An Agile Data Formatting Expert

In the AnQi CMS template,stringformatThe filter is a very practical tool that allows us to output various types of data (whether it is numbers, strings, or other complex structures) in a specific format as strings.This is particularly important when you need to embed numbers into descriptive text or need to format numbers in a specific way.

Its usage is similar to that in Go language'sfmt.SprintfA function, which uses format placeholders to control the output. For example, if you have a variable representing a numberitem.Quantityand you want to format it as a string with a unit, you can use it like this:

{{ item.Quantity|stringformat:"当前数量:%d 件" }}

Here%dIs a placeholder indicating that the number will be output in decimal integer format.stringformatIts strength lies in the fact that it can not only format integers but also handle floating-point numbers (such as%.2fNumbers represented to two decimal places, as well as other more complex string combinations, provide a neat data foundation for subsequent conditional judgments.

ifLabel: The cornerstone of conditional judgment.

AndifTags are the foundation for our conditional judgments. They allow us to execute different code blocks based on the value of variables, thereby achieving dynamic content switching. Anqi CMS templates supportif/elif(short for else if) andelseThe complete logical structure, allowing you to clearly define multiple conditions.

The basic structure is as follows:

{% if 条件A %}
    <!-- 当条件A为真时显示的内容 -->
{% elif 条件B %}
    <!-- 当条件A为假,且条件B为真时显示的内容 -->
{% else %}
    <!-- 当所有条件都为假时显示的内容 -->
{% endif %}

In conditional expressions, you can perform numerical comparisons (>/</==/>=/<=/!=), boolean judgments (true/false)String matching, even combining with other filters or logical operators(and/or/not)to build complex logic.

It is worth noting that when performing numerical comparisons, if the data source is uncertain whether it is of pure numeric type (for example, it may contain stringified numbers), it is best to useintegerorfloatThe filter converts it to the corresponding numeric type to ensure the accuracy of comparison.

Practice exercise: Dynamic display of inventory status.

Now, let's demonstrate through a common e-commerce scenario - the dynamic display of product inventory status.stringformatandifHow tags are combined to use.

Assuming our product detail page has a variableproduct.StockIt represents the current stock quantity of the product. We want to display the stock status according to the following rules:

  • If stock is greater than 10, display 'Sufficient stock'
  • If stock is between 1 and 10 (inclusive), display 'Stock is tight (only X pieces left)'
  • If the stock is 0, display 'temporarily out of stock'

The following is a specific implementation of the template code:

<div class="product-stock-status">
    {# 假设我们有一个产品库存变量:product.Stock #}
    {# 首先,使用integer过滤器确保product.Stock是一个可比较的数字 #}
    {% set currentStock = product.Stock|integer %}

    {% if currentStock > 10 %}
        <span class="status-abundant">库存充足</span>
    {% elif currentStock >= 1 and currentStock <= 10 %}
        <span class="status-tight">库存紧张(仅剩{{ currentStock|stringformat:"%d" }}件)</span>
    {% else %}
        <span class="status-out">暂时缺货</span>
    {% endif %}
</div>

In this code block:

  1. We first pass through{% set currentStock = product.Stock|integer %}Defined a temporary variablecurrentStock, and useintegerThe filter converts its value to an integer, which can effectively avoid comparison errors due to inconsistent data types.
  2. Next, the outer layer,{% if currentStock > 10 %}Check if the inventory is greater than 10, if so, output 'Inventory is sufficient.'
  3. If the first condition is not met,{% elif currentStock >= 1 and currentStock <= 10 %}it will check if the inventory is between 1 and 10. Here, a clever use ofandThe operator connects two conditions.
  4. We used it again in the description of low inventory.{{ currentStock|stringformat:"%d" }}tocurrentStockThe value is embedded in the description string, providing more specific quantity information.
  5. Finally, if none of the above conditions are met (i.e., inventory is 0 or negative),{% else %}Part of it will display "Temporarily Out of Stock".

In this way, you can not only output different string descriptions according to the size of the number, but also embed dynamic numbers accurately into these descriptions, which greatly enhances the flexibility of content display and the user experience.

Further thinking and application scenarios

This combinationstringformatandifThe pattern of tags, with extremely extensive applications in the actual operation of Anqi CMS:

  • User level displayAccording to the user's score or level value, display 'Copper Member', 'Silver Member', or 'Gold Member'.
  • Progress bar status:According to the task completion percentage, display 'Not started', 'In progress (XX%)', 'Completed'.
  • Rating starsBased on the product rating score, output different numbers of star icons or text descriptions.
  • Promotional activities: Display different promotional information such as 'No discount', 'Full reduction of X yuan', etc. based on the order amount or product quantity.

Mastering this combination usage method will make you more skillful in content management and template customization of AnQi CMS, and add more intelligence and personalized vitality to your website content.


Frequently Asked Questions (FAQ)

Q1: Why myifThe condition judgment does not take effect, or the result of the numerical comparison is incorrect?

A1: The most common reason is a mismatch in data types. The Anqi CMS template engine may cause unexpected comparison results when comparing values, if one of the values is a string type (such as '10' instead of the number 10).It is recommended to use before performing numerical comparisonintegerorfloatThe filter explicitly converts the variable to a numeric type. For example,{% set myNumber = someVariable|integer %}or{% set myFloat = someVariable|float %}.

**Q2: BesidesstringformatThere are other ways to