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 points level.stringformatfilters andifLabel.
This article will delve into how to use these two tools in the Anqi CMS template, making your website content display more intelligent and user-friendly.
stringformatFilter: A versatile data formatting wizard
In the templates of AnQi CMS,stringformatA filter is a very practical tool that allows us to output various types of data (whether numbers, strings, or other complex structures) as strings in a specific format that we define.This is particularly important when it is necessary to embed numbers into descriptive text or when specific formatting of numbers is required.
its usage is similar to that in the Go languagefmt.SprintfFunctions, control the output by specifying format placeholders. For example, if you have a variable representing a quantityitem.Quantity, and you want to format it as a string with a unit, you can use it like this:
{{ item.Quantity|stringformat:"当前数量:%d 件" }}
Here are the%dis a placeholder indicating that the value should be output in decimal integer format.stringformatis powerful because it can not only format integers but also handle floating-point numbers (such as%.2fRepresents a floating-point number with two decimal places, as well as other more complex string combinations, providing a tidy data foundation for subsequent conditional judgments.
ifLabel: the cornerstone of conditional judgment
whileifTags are the foundation for conditional judgments. They allow us to execute different code blocks based on the value of variables, thus achieving dynamic switching of content. The templates of Anqi CMS supportif/elif[else if abbreviation] andelsecomplete 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 numeric comparisons (>/</==/>=/<=/!=), boolean evaluations (true/false), string matching, and even combine 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 use first.integerorfloatThe filter converts it to the corresponding numeric type to ensure the accuracy of comparison.
Hands-on Practice: Dynamic display of inventory status
Now, let's demonstrate through a common e-commerce scenario - dynamic display of product inventory status.stringformatandifHow tags can be combined.
Assuming our product details 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 the inventory is greater than 10, display 'Sufficient Inventory'
- If the inventory is between 1 and 10 (inclusive), display 'Inventory Tight (Only X pieces left)'
- If the stock is 0, display 'Temporarily Out of Stock'
The following is the specific template code implementation:
<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:
- We first go through
{% set currentStock = product.Stock|integer %}A temporary variable is definedcurrentStockand is usedintegerThe filter converts its value to an integer, which can effectively avoid comparison errors due to inconsistent data types. - Next, the outer layer,
{% if currentStock > 10 %}Check if the stock is greater than 10. If it is, output 'Sufficient stock'. - If the first condition is not met,
{% elif currentStock >= 1 and currentStock <= 10 %}it will check if the stock is between 1 and 10. Here, a clever use ofandThe operator connects two conditions. - We have used it again in the description of stock shortage.
{{ currentStock|stringformat:"%d" }}tocurrentStockThe value is embedded into the description string, providing more specific quantity information. - Finally, if none of the above conditions are met (i.e., the stock is 0 or negative),
{% else %}part will display “Temporarily out of stock”.
In this way, you can not only output different string descriptions based on the numerical size, but also embed dynamic numbers precisely into these descriptions, greatly enhancing the flexibility of content display and user experience.
Further thinking and application scenarios
This combinationstringformatandifThe pattern of tags has extremely extensive applications in the actual operation of Anqi CMS:
- User level displayAccording to the user's points or level value, display 'Copper Member', 'Silver Member', or 'Gold Member'.
- Progress bar statusBased on the task completion percentage, display 'Not Started', 'In Progress (XX%)', 'Completed'.
- Comment ratingBased on the product rating score, output a different number of star icons or text descriptions.
- Promotional ActivityBased on the order amount or product quantity, display different promotional information such as 'No discount', 'Reduce X yuan', etc.
Mastering this combination usage method will make you more agile in content management and template customization in Anqi CMS, bringing more intelligence and personalized vitality to your website content.
Common Questions and Answers (FAQ)
Q1: Why myifcondition judgment does not work, or the comparison result of numbers is not correct?
integerorfloatThe filter explicitly converts the variable to a numeric type. For example,{% set myNumber = someVariable|integer %}or{% set myFloat = someVariable|float %}.
**Q2: BesidesstringformatThere are also other options