How to define and use temporary variables in AnQiCMS templates to simplify content display?

Calendar 👁️ 61

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 orincludeDefine 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.
  • 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.

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)

  1. {% 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.

  2. {% 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.

  3. 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

Related articles

How to automatically parse a URL string into a clickable HTML link in AnQiCMS template?

In AnQiCMS template development, we often encounter the need: the URL string contained in the content should be automatically converted into a clickable HTML link to enhance user experience and page interactivity.Manually adding links is undoubtedly cumbersome and unrealistic, fortunately AnQiCMS provides powerful template filters that can help us easily achieve this function.AnQiCMS template engine supports Django-like syntax, which includes a series of practical filters that can process variable content.For automatic parsing of URL strings

2025-11-08

How to automatically wrap long text to a specified length in AnQiCMS template?

In the presentation of website content, the way long texts are displayed is often a key factor affecting user experience and the beauty of the page.When we need to display a long text content, such as an article summary, product description, or detailed introduction, in a more readable and layout-adaptive way, AnQiCMS's template function provides a powerful and flexible solution.AnQiCMS uses syntax similar to Django template engine, with various built-in filters (Filters) that can help us easily format text.

2025-11-08

How to safely output HTML code in the template without escaping in AnQiCMS?

When using AnQiCMS for website template development or content display, you may encounter situations where you need to output HTML code directly on the page, only to find that the code is automatically escaped, for example, the `<p>` tag becomes `&lt;This often confuses those who are new to it.In fact, this is the default measure taken by the AnQiCMS template engine for website security.### Understanding the default security mechanism of AnQiCMS templates The AnQiCMS template engine design has drawn inspiration from

2025-11-08

How to truncate a string and add an ellipsis (...) to limit the display length in AnQiCMS template?

In AnQiCMS template development, we often need to refine the content displayed on the website, such as article titles, summaries, or abstracts of a text.If the content is too long, it not only affects the beauty of the page, but may also reduce the user's reading experience.AnQiCMS's powerful template engine provides a simple and efficient method to solve this problem, allowing us to easily extract strings and automatically add ellipses (...) to elegantly limit the display length of content.

2025-11-08

How to implement the link display for multi-language site switching in AnQiCMS?

In today's globalized digital world, multilingual support for websites has become crucial for reaching a wider audience and expanding market boundaries.AnQiCMS (AnQiCMS) fully understands this need, therefore, it takes multilingual support as one of its core features, aiming to help users efficiently build and manage multilingual websites.This article will focus on how to implement the display of language switch links for multi-language sites in AnQiCMS, supplemented by necessary SEO practices, and provide you with a comprehensive guide.

2025-11-08

How to add `hreflang` tags in AnQiCMS template for multilingual pages to optimize SEO?

In today's globalized internet environment, many websites need to provide content for audiences of different languages or regions.To ensure that these multilingual pages can be correctly understood and displayed by search engines, the `hreflang` tag plays a crucial role.It can tell search engines that your website has multiple language versions and which version should be displayed to which user.

2025-11-08

How does AnQiCMS call and display data for specific sites based on different site IDs?

AnQiCMS multi-site data call: easily achieve content sharing and linkage display AnQiCMS is a content management system designed specifically for small and medium-sized enterprises and content operation teams, and its multi-site management function is one of its core highlights.In actual operation, we often encounter such needs: the main station needs to display the latest products of various sub-sites, or all sub-sites need to uniformly display the contact information of the company's headquarters, or multiple content platforms hope to aggregate and display articles on a specific theme.In this case, how to efficiently call and display data from a specific site is particularly important

2025-11-08

How to enable Markdown editor in AnQiCMS and display mathematical formulas and flowcharts correctly?

Today, with the increasingly rich content creation, plain text is no longer sufficient to express complex concepts.If complex mathematical formulas in academic articles or clear process diagrams in project management can be presented intuitively on the web, it will undoubtedly greatly enhance the professionalism and user experience of the content.AnQiCMS (AnQiCMS) understands this need, through the built-in Markdown editor and flexible frontend configuration, allowing you to easily implement these advanced content displays.This article will give a detailed introduction on how to enable Markdown editor in AnQiCMS

2025-11-08