How to use `with` or `set` tags to define and assign variables in AnQiCMS templates?

Calendar 👁️ 59

The AnQiCMS template system provides strong support for content operators and developers with its flexibility and ease of use.In the content display, we often need to define some temporary variables to handle data, optimize logic, or pass parameters.withandset. Understanding their respective features and application scenarios can make your template code clearer and more efficient.

Variable definition in the template: flexibility and order

In AnQiCMS templates, variables are the basis for our data interaction.Whether it is data passed directly from the backend or temporary calculation or storage of values within the template, it cannot do without variable definition and use.{{ 变量名 }}to output variable content. AndwithandsetTags provide the ability to finely control variable lifecycle and scope during template code execution. In terms of variable naming, AnQiCMS encourages the use of camelCase naming (such asmyVariableThis helps maintain code style consistency.

withTag: The elegant way of local scope.

withThe main function of the tag is to define one or more temporary variables within a specific code block. These variables are only available in this{% with ... %}and{% endwith %}Valid between, will not pollute the external variable environment.This local scope design makes the modularization and maintainability of template code greatly improved, especially important when dealing with complex layouts or introducing public components.

For example, when we have a universal page header (header) component, it may require some specific information, such as the page title and keywords. UsingwithLabel, we can clearly pass this information toincludeThe header component introduced by the label, without worrying about conflicts with the same-named variables in the main template.

{% with title="安企CMS官网 - 轻松构建您的企业网站" keywords="AnQiCMS,企业网站,内容管理系统" %}
    {# 这里可以调用定义好的 title 和 keywords 变量 #}
    <p>当前页面标题:{{ title }}</p>
    <p>当前页面关键词:{{ keywords }}</p>
    {# 通常,我们会将这些变量传递给一个公共模板片段 #}
    {% include "partial/header.html" with title=title keywords=keywords %}
{% endwith %}

{# 在 with 标签外部,title 和 keywords 变量将不再可用,或者恢复到 with 标签定义之前的值 #}
<p>在 with 块外部,标题变量不可用或为之前的值。</p>

In the above example,titleandkeywordsvariables are onlywithExists within a block, or passed as a parameter toheader.html. OnceendwithThe label appears, these variables' lifecycles end, perfectly achieving the effect of local variables.This emphasizes the encapsulation of variables, making each code block function more independently.

setLabel: Flexible single assignment

Compared towiththe block scope of the label,setTags provide a more direct and flexible way of assigning variables. By{% set 变量名 = 值 %}You can define a variable at any position in the template, the variable will be accessible throughout the entire template from the point of definition. Its scope is the current file and it does not haveendsetLabel. This makessetLabels are an ideal choice for storing computational results, temporary data, or extracting specific values from complex structures.

Let's take a look atsetSome common uses of labels:

  1. Store simple values or calculation results:

    {# 获取当前年份并存储到 year 变量中 #}
    {% set currentYear = now "2006" %}
    <p>网站版权年份:&copy; {{ currentYear }}</p>
    
    {# 进行一些简单的算术运算并存储结果 #}
    {% set result = 10 * 5 + 3 %}
    <p>计算结果:{{ result }}</p>
    
  2. Extract specific data from complex data structures:When processing a group of images, we may only need the first image as the cover image.setLabels can help us easily achieve this.

    {% categoryDetail categoryImages with name="Images" %} {# 假设 categoryImages 包含一个图片 URL 数组 #}
    {% if categoryImages %}
        {% set pageBanner = categoryImages[0] %} {# 提取数组的第一个元素 #}
        <div class="page-banner" style="background-image: url('{{ pageBanner }}');">
            {# 背景图将使用提取出的第一张图片 #}
        </div>
    {% else %}
        <div class="page-banner-placeholder">
            {# 无图时的占位符 #}
        </div>
    {% endif %}
    
  3. Combine filter processing of data: setTags combined with AnQiCMS rich filters can bring out powerful data processing capabilities. For example, we can usesetTags store a processedcontainThe boolean value after the filter is judged, so as to make subsequent conditional judgments:

    {% set articleContent = "这是一篇关于AnQiCMS的教程文章,AnQiCMS功能强大。" %}
    {% set hasAnQiCMSKeyword = articleContent|contain:"AnQiCMS" %}
    
    {% if hasAnQiCMSKeyword %}
        <p>文章内容中包含 "AnQiCMS" 关键词。</p>
    {% else %}
        <p>文章内容中不包含 "AnQiCMS" 关键词。</p>
    {% endif %}
    

When to choosewithWhen to choose,set?

These tags are not exclusive but complementary, their choice depends on your specific needs and considerations of variable scope:

  • SelectwithTag: When you need to define a temporary variable within an independent logic block (especially one that includesincludecomponents of a tagwithit is a better choice. It enforces the use ofendwithTags are used to explicitly define the lifecycle of variables, avoiding name conflicts and unnecessary global scope pollution, making the code intent clearer and easier to maintain.It is very suitable for providing a set of clear input parameters for components.

  • SelectsetTag: When you need to define a variable at a certain point in the current template file and use it multiple times in the following code,setLabels make it more convenient.It is often used to store intermediate calculation results, extract key information from a dataset, or perform a one-time conditional assignment.As its scope is the entire current template file (starting from the definition point), it provides great flexibility, but it also needs to be careful to avoid excessive use in large and complex templates to prevent confusion in variable management.

Summary

whether it iswiththe elegant local encapsulation of tags, orsetFlexible in-place assignment of tags, they are indispensable tools for AnQiCMS template development.Mastery of these two variable definition and assignment tags will help you write more structured, powerful, easy to understand and maintain AnQiCMS template code, thus better displaying website content and improving operational efficiency.


Frequently Asked Questions (FAQ)

1.setHow is the scope of a variable defined by a tag

setThe scope of a variable defined by a tag starts from its definition and extends throughout the entire current template file. This means once you use{% set myVar = "value" %}defined a variablemyVaryou can access it at any subsequent position in the template file{{ myVar }}Visit it until the template file is rendered. It will not be automatically passed through toincludeother template files introduced by tags unless you explicitly pass it as a parameter.

2. Can IwithUsing within the tagsetCan I define a variable with tags? What will be their scope?

Yes, you can absolutely definewithUsing within the tagsetWhen defining a variable with tags. WhensetThe tag is inwithdefined inside the block, the variable will first be inwithThe label takes effect within the local scope. Ifwitha variable with the same name exists outside the blocksetInwithThe definition within the block will "shadow" the external variable. Oncewiththe block ends,setThe locally defined variables will also be invalidated, or the same ones from the outside

Related articles

The `for` loop tag can iterate over arrays, but it also supports advanced usages like `reversed` or `empty`?

## The `for` loop in Anqi CMS template: Not just iteration, but advanced techniques to help you achieve twice the content operation results As a senior website operation expert, I am well aware of the importance of an efficient and flexible content management system for enterprises.AnQiCMS (AnQiCMS) leverages its high-performance architecture based on the Go language and Django template engine syntax to provide strong support for our content creation and display.In daily operations, we often need to present data collections in the form of lists on websites, at which time, the `for` loop traversal tag is undoubtedly our reliable helper

2025-11-06

Which conditional judgment operations does the `if` logical judgment tag support in the AnQiCMS template?

As an experienced website operation expert, I am well aware that a powerful and flexible template system is crucial for the effective presentation of website content.AnQiCMS (AnQi Content Management System) takes full advantage of its high efficiency based on the Go language and the grammar features borrowed from Django template engine, providing great convenience for our content operation.In AnQiCMS template development, proficiently using logical judgment tags is the key to achieving dynamic content display and enhancing user experience.Today, let's delve into the various conditional judgment operations supported by the `if` logical judgment tag in the AnQiCMS template

2025-11-06

How does the `stampToDate` tag format timestamps into any custom date and time format?

## Mastering AnqiCMS `stampToDate`: Easily Customize Time Display Format The way time information is presented is crucial in the daily work of content operation.Whether it is the release date of an article, the time a product is listed, or the moment a comment is submitted, a clear and readable date and time format can greatly enhance the user experience.However, we often get a series of difficult-to-understand Unix timestamps from the database - like the number `1609470335`. Don't worry

2025-11-06

How to use the `breadcrumb` tag in the AnQiCMS template to generate breadcrumb navigation?

As an experienced website operations expert, I know that a user-friendly and SEO-optimized website cannot do without a clear navigation structure, and breadcrumb navigation is the key link in this regard.It can not only help users understand their current location, improve the usability of the website, but also provide clear website structure signals for search engines.In AnQiCMS, integrating and using breadcrumb navigation is very simple and efficient, which is mainly due to its built-in `breadcrumb` tag. Today

2025-11-06

How to implement code reuse and pass additional variables using the `include` tag in template development?

As an experienced website operations expert, I am well aware of the importance of template development efficiency and code maintainability for a website in my daily work.AnQiCMS (AnQiCMS) relies on its efficient architecture based on the Go language and the Django-style template engine, providing us with powerful content management capabilities.Today, let's delve deeply into a tool that can significantly improve efficiency and code reuse in Anqi CMS template development, namely the `include` tag, especially how it helps us achieve code reuse and flexibly pass additional variables.

2025-11-06

How to implement template inheritance with the `extends` tag and overwrite specific blocks of the parent template?

As an experienced website operations expert, I deeply understand that a flexible and efficient template system is crucial for the long-term development of a website.In AnQiCMS (AnQiCMS), it draws on the powerful capabilities of the Django template engine, allowing you to manage the website interface in a simple and logical way.Today, we will focus on one of the core features - the `extends` tag, and delve into how it implements template inheritance, allowing us to accurately rewrite specific blocks of the parent template.

2025-11-06

How to define and call the `macro` macro function in the AnQiCMS template to create reusable code snippets?

In the process of website operation and development, we always encounter the need to repeatedly write similar code segments, such as unified article card styles, product information display modules, or form elements with specific interactions.If you start from scratch every time, it is not only inefficient, but also makes maintenance a nightmare.AnQi CMS is well-versed in this, its powerful template engine provides us with the 'macro' macro function, a tool aimed at helping developers and operators easily create reusable code snippets

2025-11-06

How to output system information configured in the AnQiCMS template, such as website name, Logo, and filing number?

In the flexible world of AnQiCMS, elegantly presenting the system-level information configured in the background to the front end of the website is a core skill that every website operator and template developer needs to master.As an experienced website operations expert, I know that these seemingly trivial details are invaluable for enhancing brand image, optimizing user experience, and meeting regulatory requirements (such as displaying the filing number).Today, let's delve deeply into how to output these valuable background information in the AnQiCMS template in a natural and smooth manner. AnQiCMS

2025-11-06