When using AnQiCMS for website content management, the flexibility of templates is crucial for achieving diverse content display.At times, we not only need to output data directly, but also need to perform some temporary processing, calculation, or judgment based on business logic, at which point defining temporary variables in the template becomes particularly useful.This not only makes the template code more neat, but also avoids repeated retrieval or calculation of the same data, thereby improving rendering efficiency and maintainability.
The Anqi CMS template engine syntax is similar to the Django template engine, providing powerful variable definition and logical control capabilities, where temporary variables are mainly defined through{% with %}and{% set %}These two tags can be used. Understanding their usage and scope can help us better build complex and expressive website templates.
Use{% with %}Tag: Local scope temporary variable
{% with %}Tags are mainly used to temporarily define one or more variables within a specific block of a template. The variables created are only valid within the{% with %}and{% endwith %}blocks. A typical use case for it is to{% include %}Labeling the child template passes additional variables, and these variables may not be globally available or 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:
Assume you have a public header template filepartial/header.htmlIn which a dynamically generated title and keywords need to be displayed, and this information may be different on each page. You can do this:
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>In
partial/header.htmlUsing:<head> <title>{{ custom_title }}</title> <meta name="keywords" content="{{ custom_keywords }}"> <!-- 其他头部元素 --> </head>By
{% with %}, you can ensurecustom_titleandcustom_keywordsThese two variables are only inheader.htmland its containing{% with %}Valid within the block, avoiding variable name conflicts and maintaining code modularity.
Moreover, you can also in{% with %}make some temporary logical judgments within the block, such as:
{% 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 statement within the current template
{% set %}Labels allow you to declare a variable in the current template file, and after the declaration, this variable can be used anywhere in the current template (including nested templates).{% block %}or{% for %}visited and used in a loop until the template rendering is finished. Its scope is broader{% with %}and is suitable for scenarios where multiple uses or complex calculations are needed within the current template.
Syntax structure:
{% set variable_name = "值" %}
<!-- 在当前模板的后续部分使用 {{ variable_name }} -->
Actual application example:
Simplify complex expressions:When you need to extract a value multiple times from a deeply nested object, use
{% set %}It 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>Store the filtered results:The AnQi CMS provides rich filters, if you need to perform multiple filtering operations on the same data and store the final results.
{% set %}is the 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 were then truncated to the first 100 characters, and the processed result was assigned tobrief_description.Cumulative calculation is performed in the loop:If you are in a
{% for %}In a loop, you need to perform cumulative calculations for some data,{% set %}which can help you achieve it.{% 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 should which be used?
Select{% with %}Or{% set %}It mainly depends on your need for variable scope:
- Use
{% with %}:When you only need to be ina specific code block.For example, a<div>complex logic within a tag, or when passing information to{% include %}a sub-template. This helps to maintain the locality of variables and avoid unnecessary global pollution. - Use
{% set %}:When you need toWithin a broader scope of the current template fileUsed when a variable is needed, or when continuous calculations and data transformations are required. It provides a way to define and reuse complex values in templates.
In summary,{% with %}emphasize the 'temporariness' and 'locality' of variables, while{% set %}The variable focuses more on the 'declaration' and 'reusability' within the current template. Mastering these tags will make your Anqie CMS template development more efficient and organized.
Frequently Asked Questions (FAQ)
Q1:{% with %}and{% set %}What is the essential difference between defined variables?
A1:The main difference between them lies in the variableScope.{% with %}The defined variable is only valid in its own{% with %}to{% endwith %}block or when it is passed throughwithpass the parameter to{% include %}Valid in the child template, it belongs to the local scope. And{% set %}The defined variable can be used at any subsequent position in the current template file after it is declared, including within any loop or conditional judgment it is in, until the rendering of the current template file ends.
Q2: Can I use{% for %}Define in a loop{% set %}Do you want to add variables and accumulate operations?
A2:Of course you can.{% set %}Variables are very suitable for accumulating, counting, or performing other iterative data processing operations within loops. As shown in the example article, you can initialize a{% set total_price = 0 %}variable, and then use it within the loop body{% set total_price = total_price|add:item.price %}This way of accumulating.
Q3: If I define a temporary variable but it 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 usually does not report an error when accessing non-existent variables or object properties, but treats them as empty values (such as empty strings or zeros). However, for code robustness and to avoid unexpected displays, you can usedefaultordefault_if_noneThe filter sets a default value for it. For example:{% set username = user.Name|default:"匿名用户" %}So even ifuser.NameIf it does not exist, it will also display "Anonymous user".