When developing templates in AnQiCMS, we often encounter situations where we need to process some complex data or reuse a certain calculation result. To make the template code more concise, readable, and easy to maintain, AnQiCMS provides a powerful mechanism for defining and using temporary variables, mainly throughwithandsetThese tags to achieve. Properly using them can greatly improve the efficiency and flexibility of our content display.
Simplified content display: why do we need temporary variables?
Imagine if we need to display the same attribute of a piece of data multiple times in a template, such as the thumbnail URL of an article or a category description.Each time it is obtained through long labels, not only does the code look cumbersome, but it is also very麻烦 to modify once the data source or processing logic changes.In addition, some expressions are inherently complex, such as the need to format timestamps or extract the first image from a list of images as a cover.At this time, if these intermediate results can be stored in a temporary 'short name', and then referred to in the template with this short name, it will undoubtedly make the template logic clearer.
AnQiCMS's template engine is similar to Django, it allows us to output data by{{变量名}}and control logic by{% 标签 %}. On this basis,withandsetLabels are like 'assistants' in our templates, helping us store and manage intermediate data.
Use{% with %}Label: Graceful transmission in the local scope
withThe tag is mainly used to define one or more temporary variables within a specific code block. Its core feature is 'local scope', which means that variables defined throughwithare only accessible within{% with %}and{% endwith %}This is valid between the tags. Once outside of this code block, these variables will become invalid.
Basic syntax:
{% with 变量名1=值1 变量名2=值2 %}
<!-- 在这里使用 {{变量名1}} 和 {{变量名2}} -->
{% endwith %}
withOne of the most common uses of tags is to giveincludeThe template passes variables. When we introduce a common header or footer, we may need to pass some specific information, such as the title or keywords of the current page.
Example: Pass variables to the header includedAssuming we have apartial/header.htmlSubtemplate, it needs to display the page title and keywords.
In the main template, we can use it like thiswithto pass:
{% include "partial/header.html" with title="我的文章详情" keywords="AnQiCMS, 模板变量" %}
and in thepartial/header.htmlYou can use these variables directly:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<meta name="keywords" content="{{keywords}}">
<!-- 其他头部内容 -->
</head>
<body>
This method ensures the independence of the sub-template and also makes the logic of the main template clearer. At the same time, if you only need to pass specific variables and do not want the sub-template to access all the variables of the main template, you can also inwithAdd afteronlyKeyword to limit.
withAnother advantage of tags is to simplify the temporary storage of complex expressions. For example, we fromarchiveDetailGot a URL of an image, which needs to be used as a background image and may be used in multiple places.
{% with articleLogo=archiveDetail with name='Logo' %}
<div class="article-header" style="background-image: url('{{articleLogo}}');">
<!-- ... -->
</div>
<img src="{{articleLogo}}" alt="文章Logo" class="article-logo">
{% endwith %}
Here, articleLogoThis temporary variable is onlywithBlock scope takes effect, effectively avoiding repeated code or overly long expressions.
Use{% set %}Tag: More flexible variable definition
Compared towithThe local scope of tags,setTags provide a more flexible way to define variables. BysetA variable defined, whose scope starts from the point of definition, until the end of the current template file, or until another variable with the same name is encounteredsetThis means reassignment to the variable stops.setThe defined variable can be used in a wider range within the template file.
Basic syntax:
{% set 变量名 = 值 %}
setTags are particularly suitable for storing some information that needs to be reused in different areas of the template, or after complex calculations and filter processing.
Example: Store formatted time.Assuming we want to display the creation time of the article and need to format it as "year-month-day". If each entry in the article list needs to be displayed, then repeatedly call{{stampToDate(item.CreatedTime, "2006-01-02")}}It will be繁琐.
{% archiveList archives with type="list" limit="5" %}
{% for item in archives %}
{% set formattedDate = stampToDate(item.CreatedTime, "2006-01-02") %}
<div class="article-item">
<h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
<p>发布日期: {{formattedDate}}</p>
<!-- 其他地方也可以使用 formattedDate -->
</div>
{% endfor %}
{% endarchiveList %}
Here, formattedDateThe variable will be reassigned in each loop iteration and can be used in the subsequent part of the current loop until the next iteration begins.
Example: Extract image and reuseOn the category details page, if multiple Banner images are uploaded, we may only want to extract the first one as the background image of the page.
{% categoryDetail bannerImages with name="Images" %}
{% if bannerImages %}
{% set pageBanner = bannerImages[0] %} {# 提取第一张图并赋值给 pageBanner #}
{% endif %}
<div class="page-banner" style="background: url('{{pageBanner}}') no-repeat center center / cover;">
<!-- Banner 内容 -->
</div>
<div class="page-intro">
<!-- 在这里,pageBanner 仍然有效 -->
<img src="{{pageBanner}}" alt="分类封面" class="intro-thumb">
<!-- ... -->
</div>
HerepageBannerVariable is insetAfter definition, it can be used in subsequentdivelements without having to extract it again, greatly improving the conciseness and efficiency of the code.bannerImages[0]extracted, greatly improving the conciseness and efficiency of the code.
withwithsetchoice: when to use which?
SelectwithOrsetIt mainly depends on your need for variable scope:
Use
{% with %}:- When you need to be within a local code block (such as a specific HTML component or
includeDefine a temporary variable when a sub-template is used, and these variables do not need to be used outside the code blockwithis the ideal choice. - Its local scope helps avoid variable name conflicts and maintain code modularity.
- When you need to be within a local code block (such as a specific HTML component or
Use
{% set %}:- When you define a variable that needs to be referenced multiple times across a template file (from the point of definition to the end of the file) or when you need to store a computed, filtered result for later use,
setIt is more suitable. - It provides greater flexibility, but also pay attention to the possibility of variable name conflicts, especially in large template files.
- When you define a variable that needs to be referenced multiple times across a template file (from the point of definition to the end of the file) or when you need to store a computed, filtered result for later use,
We usually combine these two tags to achieve **template organization and content display effects. ThroughsetDefine some global page data, and then throughwithDefine more specific auxiliary variables in the local component to achieve a clear and easy-to-manage template structure.
Summary
AnQiCMS'withandsetLabels are indispensable tools in template development.They can help us effectively manage the data in the template, encapsulating complex data processing logic into concise variables, thereby greatly enhancing the readability, maintainability, and development efficiency of the template code.Mastering their usage will make you more skilled in the content operation of AnQiCMS, easily building high-quality, flexible and versatile content display pages.
Frequently Asked Questions (FAQ)
{% set %}Can the defined variables be passed through?{% include %}Can the introduced sub-template be used?Generally speaking,{% set %}Variables are defined to be effective only within the current template file, and will not be automatically passed toincludethe included sub-template. If you need to use it in the sub-template, you need to pass it through{% include "partial/header.html" with myVariable=someValue %}the way to explicitly pass variables as parameters.{% with %}and{% set %}defined variables within a loop (forlabel) are different?{% with %}defined variables, whose scope is limited to the currentwithblock. If used inside a loopwithdefining a variable, then this variable will be redefined every iteration of the loop and will expire at the end of thewithblock.{% set %}A variable defined, whose scope starts from the point of definition. If used outside of a loopsetDefine a variable, then the variable maintains its value throughout the loop, unless it is reassigned within the loopsetRerun the assignment. If used within the loopsetDefine a variable, and the scope of the variable is also limited to the current loop iteration, but it can be used at any position within that iteration.Can complex data structures such as lists or objects be stored in temporary variables?Yes, the AnQiCMS template engine allows you to in
{% set %}or{% with %}Store complex data structures, such as througharchiveListOr retrieve a document list,tagDetailThe obtained label object. You can assign these complex objects to temporary variables and then access their properties or iterate over them as usual. For example,{% set myArchives = archives %}After that, you can handle it like thisarchivesHandle it like thismyArchivesyou can directly use