In AnQiCMS templates, flexibly customizing and using variables is the key to achieving dynamic content and efficient template reuse.AnQiCMS's template syntax borrows the characteristics of popular template engines such as Django and Blade, making variable definition and assignment intuitive and powerful.withandsetThese tags help you better customize variables and make use of them in AnQiCMS templates.
I. The Foundation of Variable Customization: Understanding the Core of Template Syntax
In AnQiCMS templates, you will frequently encounter two core syntax structures:
- Double curly braces
{{ 变量 }}: is used to directly output the value of a variable. - Single curly braces and percentage signs
{% 标签 %}English: Used to perform logical operations, such as conditional judgments, loops, variable assignments, etc.
It is through{% 标签 %}ofwithandsetWe can create and manage variables within the template to achieve more refined content control and flexible layout design.
Second,withLabel: Inject data into the temporary context
withLabels are used to create a temporary variable scope, within which variables defined are only effective{% with %}and{% endwith %}in between. Its most common use is to cooperate withincludeLabel, pass specific data to the template fragment being included without polluting the global template environment.
Working principle:
When you usewithWhen you label, you are actually defining a set of temporary variables for the next segment of template code. These variables will override or supplement variables with the same name in the current scope, but once{% endwith %}Labels appear, these temporary variables will be cleared, and the template will return to the previous variable environment.
Use cases:
to
includetemplate passes parameters:Assuming you have a generalheader.htmlTemplate, which includes the website title and keywords. These values may vary on different pages.{# index.html 页面 #} {% with page_title="首页标题 - AnQiCMS" page_keywords="AnQiCMS, 模板, 变量" %} {% include "partial/header.html" with title=page_title keywords=page_keywords %} {% endwith %} {# partial/header.html 模板内容 #} <head> <title>{{ title }}</title> <meta name="keywords" content="{{ keywords }}"> </head>In this example,
index.htmlPasswithDefinedpage_titleandpage_keywordsThen, use them astitleandkeywordsPass toheader.html.header.htmlThese variables will only be used when they are included.Create temporary data for a specific block:If there is a small section of complex logic or data display in the template,
withencapsulate it in a block to avoid variable name conflicts and maintain code neat.{% with featured_article_id=10 %} {# 在这里调用ID为10的特色文章数据 #} {% archiveDetail featured with name="Title" id=featured_article_id %} <h3>特色文章: {{ featured }}</h3> {% endwith %} {# featured_article_id变量在此处已失效 #}
Caution:
withThe variable defined by the label is only valid{% with %}and{% endwith %}between.- If passed to
includeThe variable name of thewithdefined variable name is the same, the latter will overwrite the former. withThe label supports defining multiple variables at the same time, separated by spaces.key=valueYes.
III,setLabel: Build flexible local variables
setTags are the most commonly used and most direct variable assignment method in AnQiCMS templates.It allows you to declare a variable at any position in the template and assign it a value. This variable will be available throughout the entire scope of the current template, unless it is overridden by a deeper scope.
Working principle:
setLabel uses{% set 变量名 = 值 %}The concise form, directly assigns the value on the right to the left variable. This value can be a literal, another variable, the result of an expression, or even data processed by a filter.
Use cases:
Store computation results:When you need to perform calculations or filtering on data, and use the results for multiple subsequent outputs,
settags are very convenient.{# 假设item.CreatedTime是一个时间戳,您想将其格式化 #} {% set publish_date = stampToDate(item.CreatedTime, "2006-01-02") %} <p>发布日期: {{ publish_date }}</p> <p>文章更新于: {{ publish_date }}</p> {# 可以多次使用 #} {# 结合过滤器进行字符串处理 #} {% set article_description = item.Description|truncatechars:100 %} <p>摘要: {{ article_description }}</p>Here,
publish_dateandarticle_descriptionThe variable passes throughsetAfter defined, it can be referenced at any subsequent position in the template.Handle complex data structures:When you need to extract specific data from a complex object and simplify its access method,
setCan be put to use.{# 假设 archive.Images 是一个图片URL数组,我们只想取第一张图 #} {% set first_image = archive.Images|first %} {% if first_image %} <img src="{{ first_image }}" alt="{{ archive.Title }}"> {% endif %} {# 获取自定义字段 #} {% set custom_author = archive.CustomFields.Author %} {% if custom_author %} <p>作者: {{ custom_author }}</p> {% endif %}As a middle variable for conditional judgment:Simplify
ifThe complexity of the statement.{% set is_premium_user = user.Level >= 5 %} {% if is_premium_user %} <p>欢迎尊贵的VIP用户!</p> {% endif %}
Caution:
setThe variable defined by the tag is available in the entire scope of the current template starting from the line of definition.- Not unlike
with,setIt is not necessaryendsetLabel. - If used multiple times
setAssigning the same variable repeatedly will overwrite the previous assignments.
IV. Selection and Application:withWithsetof the strategy
UnderstoodwithandsetThe characteristics after, we can flexibly choose according to actual needs:
- Use
with: When you need to pass a set of specific variables to a beingincludeWhen creating a temporary, independent environment for a template fragment, or for a small section of template code,withIt is an ideal choice. It helps to encapsulate variables, avoid pollution of global variables, and enhance the maintainability of templates. - Use
setWhen you need to create, store, or process variables in the current template file and plan to reference these variables in multiple locations later on,setIt is more practical. It performs excellently in data preprocessing, simplifying complex expressions, and storing intermediate calculation results.
These two tags are not exclusive, they can be used together very well, and together they can build a powerful and clear AnQiCMS template.
V. Outputting Variables and Debugging
No matter which one you usewithOrsetDefined a variable, all of which can be accessed through double curly braces{{ 变量名 }}to output its value.
In the process of template development,