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

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,