How to customize variables and assign values using (with/set) in AnQiCMS templates?

Calendar 👁️ 75

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.This article will delve intowithandsetThese tags help you better customize variables and make use of them in AnQiCMS templates.

I. The cornerstone of variable customization: understanding the core syntax of templates

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 percent signs{% 标签 %}Used to perform logical operations, such as conditional judgments, loops, and variable assignments, etc.

It is through{% 标签 %}ofwithandsetWe can create and manage variables within the template to achieve finer content control and more flexible layout design.

Second,withTag: Inject data into the temporary context

withTags are mainly used to create a temporary variable scope, within which variables defined are only valid{% with %}and{% endwith %}within. Its most common use is to cooperate withincludeTags, pass specific data to the template fragment being introduced without polluting the global template environment.

Working principle:

When you usewithWhen you label, you are actually defining a set of temporary variables for the following template code. These variables will override or supplement the variables with the same name in the current scope, but once{% endwith %}The tag appears, these temporary variables will be cleared, and the template will return to the previous variable environment.

Usage scenario:

  • ToincludeTemplate parameters:Assuming you have a generalheader.htmlTemplate that includes website title and keywords. You may want these values to change 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.htmlBywithDefinedpage_titleandpage_keywordsThen they will be used astitleandkeywordspass toheader.html.header.htmlThese variables will only be used when included.
  • Create temporary data for a specific block:If there is a small piece of complex logic or data display in the template, you can encapsulate it inwithto 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变量在此处已失效 #}
    

Note:

  • withThe variable defined by the tag is only valid within{% with %}and{% endwith %}.
  • If the variable name passed toincludethe tag matcheswiththe variable name defined in it, the latter will overwrite the former.
  • withTags support defining multiple variables at the same time, separated by spaceskey=valueRight.

Third,setTag: Build flexible local variables

setThe tag is 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 a value to it, the variable will be available in the entire scope of the current template starting from the definition position (unless it is overridden by a deeper scope).

Working principle:

setTags use{% set 变量名 = 值 %}The concise form, directly assigning the value on the right to the variable on the left. This value can be a literal, another variable, the result of an expression, or even data processed by a filter.

Usage scenario:

  • Store the calculation result:When you need to perform data calculation or filtering, and use the result 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 throughsetAfter definition, 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,setit can be very useful.
    
    {# 假设 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:simplifyifThe complexity of the statement.
    
    {% set is_premium_user = user.Level >= 5 %}
    {% if is_premium_user %}
        <p>欢迎尊贵的VIP用户!</p>
    {% endif %}
    

Note:

  • setThe variables defined by the tag are available in the entire scope of the current template starting from the definition line.
  • notwith,setNot requiredendset.
  • If used multiple timessetAssigning the same variable, the later assignments will overwrite the earlier ones.

Chapter 4: Selection and Application:withwithsetstrategy

UnderstoodwithandsetAfter understanding the characteristics, we can flexibly choose according to actual needs:

  • UsewithWhen you need to pass a set of specific variables to a template fragment, or create a temporary, isolated environment for a short segment of template code,includewhen, or to create a temporary, isolated environment for a small segment of template code.withIt is an ideal choice. It helps to encapsulate variables, avoid global variable pollution, and enhance the maintainability of the template.
  • Useset: When you need to create, store, or process variables in the current template file, and plan to reference these variables at multiple positions later,setIt is more practical. It excels in data preprocessing, simplifying complex expressions, storing intermediate calculation results, and other aspects.

These two tags are not mutually exclusive, and they can be used together very well to build a powerful and clear AnQiCMS template.

5. Output and debugging of variables

No matter which one you usewithOrsetDefined variables, all can be accessed through double curly braces{{ 变量名 }}To output their values.

During template development,

Related articles

How to display the current time and formatted timestamp in AnQiCMS template?

Displaying time on the website content, whether it is the publication date of the article, the update time of the product, or the real-time loading time of the page, can greatly enhance the user experience and the timeliness of information.AnQiCMS is a content management system developed based on the Go language, which is very intuitive and flexible in handling time and dates in templates.This article will introduce you to how to display the current time and formatted stored timestamp in AnQiCMS templates.

2025-11-07

What are the application scenarios of AnQiCMS template macro functions (macro) and include tags?

In AnQiCMS template development, in order to improve code reusability and reduce maintenance costs, we often use some powerful template functions, among which 'macro function' and 'Include tag' are two great assistants.They each have unique advantages and applicable scenarios. Understanding and appropriately applying them can make template development twice as efficient and build efficient, easy-to-maintain websites.

2025-11-07

How to implement page skeleton reuse through inheritance in AnQiCMS templates?

In website construction and operation, we often face a challenge: how to ensure the consistency of the overall style of the website while being able to flexibly modify the specific content of each page, and at the same time, taking into account the development efficiency and the convenience of later maintenance?AnQiCMS provides a powerful and intuitive template inheritance mechanism, which is the core of solving these problems.It's like creating a "template" for your website, allowing you to easily reuse common structures and focus on content creation.

2025-11-07

How to include external HTML fragments in AnQiCMS templates?

When building website templates in AnQiCMS, we often encounter some HTML code blocks that need to be reused, such as the website header, footer, sidebar navigation, advertisement slots, or some general content modules.If each time you repeat writing these codes in different template files, it is not only inefficient but also very麻烦 to find and update them one by one when modifications are needed.

2025-11-07

How to use the `archiveList` tag to display the latest article list on the AnQiCMS homepage?

On AnQiCMS, the homepage is often the first window visitors use to understand the website's content.How to efficiently and dynamically display the latest articles to attract visitors to continue browsing is the key to content operation.AnQiCMS provides a flexible and easy-to-use template tag system, where the `archiveList` tag is the core tool to achieve this goal.

2025-11-07

How to retrieve the list of articles under a specified category and implement pagination in AnQiCMS?

In website content operation, we often need to display articles under specific categories and provide pagination for these lists to enhance user experience and website loading efficiency.AnQiCMS (AnQiCMS) with its flexible template engine and powerful tag system can easily meet this requirement. AnQiCMS template system adopts syntax similar to Django template engine, using double curly braces `{{variable}}` to reference variables, as well as single curly braces with a percent sign `{% tag %}` to call tags.This makes the customization of content display very intuitive

2025-11-07

What are the commonly used fields that can be called with the `archiveDetail` tag on the article detail page?

AnQiCMS (AnQiCMS) provides great convenience for website operators with its flexibility and powerful content management capabilities.When we carefully craft an article or product page and hope to accurately display its colorful content to visitors, the `archiveDetail` tag is an indispensable tool at our disposal.It is like a treasure trove of information, allowing us to easily call up all related data of the current content on the article detail page.

2025-11-07

How to display the link to the previous and next article on the AnQiCMS article detail page?

To add links to the previous and next articles on the article detail page in AnQi CMS is a very practical feature for enhancing user reading experience and the internal link structure of the website.AnQiCMS's powerful template tag system makes this feature intuitive and efficient.

2025-11-07