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