When using AnQiCMS for website content management, the flexibility of the template is crucial for realizing diverse content display.很多时候,我们不仅仅需要直接输出数据,还需要根据业务逻辑对数据进行一些临时性的处理、计算或判断,这时候,在模板中定义临时变量就显得尤为实用。This not only makes the template code more concise, but also avoids repeated retrieval or calculation of the same data, thereby improving rendering efficiency and maintainability.

The template engine syntax of AnQi CMS is similar to Django, providing powerful variable definition and logical control capabilities, among which defining temporary variables mainly can be done by{% with %}and{% set %}These tags are used to implement. Understanding their usage and scope can help us better build complex and expressive website templates.

Use{% with %}Tag: Temporary variable in local scope

{% with %}Tags are mainly used to temporarily define one or more variables within a specific block of a template. The variables it creates are only valid between blocks.{% with %}and{% endwith %}One typical use case for it is to{% include %}The label introduces a sub-template that passes additional variables, and these variables may not be globally available or may need to be calculated temporarily.

Syntax structure:

{% with variable_name = "值" %}
    <!-- 在这里使用 {{ variable_name }} -->
{% endwith %}

Or define multiple variables at the same time:

{% with var1 = value1 var2 = value2 %}
    <!-- 在这里使用 {{ var1 }} 和 {{ var2 }} -->
{% endwith %}

Actual application example:

Suppose you have a public header template filepartial/header.htmlIn which, a dynamically generated title and keywords need to be displayed, and this information may differ on each page. You can do it like this:

  1. Define and pass in the main template:

    {% set page_specific_title = "我们的产品详情" %}
    {% set page_specific_keywords = "产品,详情,安企CMS" %}
    
    
    {% with custom_title = page_specific_title custom_keywords = page_specific_keywords %}
        {% include "partial/header.html" with custom_title custom_keywords %}
    {% endwith %}
    
    
    <main>
        <!-- 页面主体内容 -->
    </main>
    
  2. Inpartial/header.htmlUsing:

    <head>
        <title>{{ custom_title }}</title>
        <meta name="keywords" content="{{ custom_keywords }}">
        <!-- 其他头部元素 -->
    </head>
    

    Pass{% with %}, you can ensurecustom_titleandcustom_keywordsThese variables are onlyheader.htmland its enclosing{% with %}block is valid, avoiding variable name conflicts and maintaining code modularity.

Additionally, you can also perform some temporary logic judgments inside.{% with %}For example: some temporary logic judgments inside a block.

{% with is_new_product = (product.CreatedTime > (now|date:"U") - 86400) %} {# 假设判断是否为24小时内发布的新产品 #}
    {% if is_new_product %}
        <span class="badge new-product">新品上市!</span>
    {% endif %}
    <h3>{{ product.Title }}</h3>
{% endwith %}

Use{% set %}Label: flexible declarations within the current template.

{% set %}The label allows you to declare a variable within the current template file, and this variable can be used anywhere within the current template (including nested templates) after it is declared.{% block %}or{% for %}Visited and used in the loop) until the template rendering ends. Its scope is wider,{% with %}suitable for scenarios that require multiple uses or complex calculations within the current template.

Syntax structure:

{% set variable_name = "值" %}
<!-- 在当前模板的后续部分使用 {{ variable_name }} -->

Actual application example:

  1. Simplify complex expressions: Use it when you need to extract a value multiple times from a deeply nested object:{% set %}Can greatly simplify the code.

    {% set category_name = archive.Category.Title %}
    <p>所属分类:<a href="{{ archive.Category.Link }}">{{ category_name }}</a></p>
    <p>您正在浏览的文档位于 "{{ category_name }}" 分类下。</p>
    
  2. Store the results after filtering: The autoCMS provides a variety of filters, if you need to perform multiple filtering operations on the same data and store the final results,{% set %}it is an ideal choice.

    {% set brief_description = archive.Description|striptags|truncatechars:100 %}
    <p>{{ brief_description }} <a href="{{ archive.Link }}">查看更多</a></p>
    

    Here, we first removed,DescriptionThe HTML tags in, then截取了前100个字符,and the processed result is assigned tobrief_description.

  3. In the loop, cumulative calculations are performed:If you are in a{% for %}In a loop, you need to accumulate some data.{% set %}It can help you achieve that.

    {% set total_price = 0 %}
    {% for item in cart.Items %}
        <p>{{ item.Name }} - 数量:{{ item.Quantity }} - 单价:{{ item.Price }}</p>
        {% set total_price = total_price|add:(item.Quantity * item.Price) %} {# 使用add过滤器进行数值累加 #}
    {% endfor %}
    <p>购物车总价:{{ total_price }}</p>
    

When to use which?

Choose{% with %}Or{% set %}It mainly depends on your needs for variable scope:

  • Use{% with %}:When you only need toA specific code block insideFor example, a<div>Complex logic inside a tag, or something to be passed to{% include %}The child template uses temporary variables. This helps to maintain the locality of variables and avoid unnecessary global pollution.
  • Use{% set %}:When you need toA wider scope within the current template file.When using a variable, or when continuous calculation and data transformation are required. It provides a way to define and reuse complex values in templates.

In short,{% with %}Emphasizes the "temporariness" and "locality" of variables,{% set %}Then it is more focused on the 'declaration' and 'reuse' of variables within the current template. Proficiently using these two tags will make your CMS template development more efficient and organized.


Common Questions (FAQ)

Q1:{% with %}and{% set %}What is the essential difference between defined variables?

A1:The main difference between them is thescope.{% with %}Defined variables are only valid in their own{% with %}to{% endwith %}block, or when they are passed throughwithPassed to the parameter{% include %}valid in the sub-template, which belongs to the local scope.{% set %}The defined variable can be used at any subsequent position within the current template file after it is declared, including within any loops or conditional judgments it is part of, until the rendering of the current template file ends.

Q2: Can I{% for %}Do you define a loop and perform an accumulation operation?{% set %}Do you define a variable and perform an accumulation operation?

A2:Of course you can.{% set %}Variables are very suitable for accumulating, counting, or other data processing in iterative processes. As shown in the example article, you can initialize a{% set total_price = 0 %}variable, and then in the loop body through{% set total_price = total_price|add:item.price %}Perform the addition in this way.

Q3: If I define a temporary variable that may not have a value (for example, an object property does not exist), will it cause an error? How should I handle it?

A3:The template engine of AnQi CMS does not usually report an error directly when accessing non-existent variables or object properties, but treats them as empty values (such as empty strings or zero). However, to ensure code robustness and avoid unexpected displays, you can usedefaultordefault_if_noneFilter sets the default value for it. For example:“{% set username = user.Name|default:"匿名用户" %}so even ifuser.NameDoes not exist, but will also display “Anonymous user”.”} ]