How to use with or set tags in AnqiCMS templates to define variables for optimizing content display and maintenance?

In AnqiCMS template development, in order to make our website content display more flexible and code more maintainable, the definition and use of variables are indispensable skills. The system uses syntax similar to Django template engine, among whichwithandsetTags are what we define as variables, the powerful assistants for optimizing content display and managing templates. Understanding and using them effectively can greatly enhance the operation of your website.

Why do we need to define variables in the template?

Imagine that your website has multiple pages that need to display the same company phone number or copyright information, or that you need to perform some temporary calculations or formatting in a specific content block.If you always hard-code information into templates or repeat the same processing logic, then when information needs to be updated, you have to modify each page one by one, which is not only inefficient but also prone to errors.

Defining variables in the template can help us:

  1. Improve code readability and cleanliness:Translate complex data processing or repetitive values into meaningful variable names to make template code clear.
  2. Enhance content maintainability:Manage key information centrally, and you only need to update the variable definition in one place once it needs to be modified.
  3. Promote template reuse:CombineincludeLabels, passing dynamic content through variables to make generic template fragments adaptable to different display needs.
  4. Optimize content display logic:Perform secondary processing on data obtained from the backend to ensure that the front-end display meets expectations and avoids hardcoding logic directly in HTML.

Next, we will delve deeper intosetandwithThe specific usage and applicable scenarios of these tags.

set: A tool for defining local variables.

setThe tag is used to define a local variable within the current template file, and the lifetime of this variable is limited to the current template block in which it is defined and used.It is very suitable for handling temporary calculation results, intermediate data, or temporarily storing a value in a loop.

Basic usage:

You can use it to{% set 变量名 = 表达式 %}Define a variable in this way. For example, if you want to store a calculation result:

{% set total_items = archiveList.length + pageList.length %}
<p>网站共有 {{ total_items }} 篇文章和页面。</p>

In this example,total_itemsThe variable is only valid in the current template, convenient for you to refer to in the following content.

setThe label variable can also be in different scopes such asblockorforThis assignment is typically effective only within its scope, and does not affect the value of the same-named external variables, unless in certain specific scenarios (such as in inheritance templates).

{% set site_title = "AnqiCMS演示站" %}

<header>
    <h1>{{ site_title }}</h1>
</header>

{% block content %}
    {% set section_title = "最新文章" %}
    <p>当前板块标题:{{ section_title }}</p>
    {# ... 文章列表内容 ... #}
{% endblock %}

<footer>
    <p>版权所有 © {{ site_title }}</p> {# 这里的 site_title 仍然是 "AnqiCMS演示站" #}
</footer>

As you can see,section_titleonlycontenteffective within a block. This locality makessetan ideal choice for managing internal variables within templates, helping to avoid name conflicts between different template fragments.

withThe bridge between templates and local shared variables

withTags provide a way to be included within a specific code block or towards the inclusion ofincludeThe way variables are passed in template files. It creates a temporary variable scope, whenwiththese temporary variables are cleared when the code block ends.withTags are particularly suitable for when you need to provide a set of variables for a specific piece of content, or pass dynamic data to a public template snippet (such as a header, sidebar).

Basic usage:

withTags need to be associated withendwithThe tag is used in pairs, the variable definitions within the code block it wraps are visible to the block and the template files it contains.

{% with welcome_message="欢迎来到我们的网站!" site_slogan="您的内容管理专家" %}
    <header>
        <h1>{{ welcome_message }}</h1>
        <p>{{ site_slogan }}</p>
    </header>
{% endwith %}

{# 这里访问 welcome_message 或 site_slogan 将会出错,因为它们的作用域已结束 #}

withThe most common use of the tag is to cooperate withincludeLabel, pass parameters to the included template file.This allows your universal template fragment (such as a universal article card component or navigation menu) to receive different data, achieving high reusability.

Suppose you have apartial/article_card.htmlThe template fragment:

{# partial/article_card.html #}
<div class="article-card">
    <img src="{{ card_image }}" alt="{{ card_title }}">
    <h3><a href="{{ card_link }}">{{ card_title }}</a></h3>
    <p>{{ card_description }}</p>
</div>

You can reference and pass data like this in the main template:

{% include "partial/article_card.html" with
    card_image=item.Thumb
    card_title=item.Title
    card_link=item.Link
    card_description=item.Description
%}

BywithPassing variables,article_card.htmlTemplate fragments can be reused in different article lists or detail pages, displaying different article information, greatly enhancing the modularization and maintainability of the template. You can even useonlyKeyword restrictionincludeOnly accepts passwithPass the variable, to avoid unexpected global variable interference.

{% include "partial/header.html" with title="我的自定义标题" keywords="SEO关键词" only %}

This will ensureheader.htmlCan only access intitleandkeywordsThese two variables.

setwithwithWhen to choose which one?

SelectsetOrwithIt mainly depends on the scope requirements and usage scenarios of the variables:

  • SelectsetWhen:

    • You need to define a temporary variable within a template file for a specific range of logic (such as a loop or a block).
    • Variables do not need to be passed to the included template files, or the included template files will obtain data through other more general methods (such as context variables).
    • You need to perform some temporary numerical calculations, string concatenation, or data transformation, and store the result for later use.
  • SelectwithWhen:

    • You need to create a set of temporary variable contexts for a specific block in the template.
    • You want to pass explicit, dynamic parameters to a template fragment throughincludea tag to a general template fragment. This iswithThe core advantage of the label, it can make your template component more 'plug and play'.
    • You hope the scope of the variable is strictly limited to{% with %}and{% endwith %}to avoid affecting the external environment.

Examples of actual application scenarios

In the daily operation of AnqiCMS,setandwiththe application of tags is everywhere:

  1. Unified website header information:Assuming your website headerheader.htmlNeed to dynamically display the current page title (which may include category names, article names, etc.), and set different SEO keywords and descriptions for different pages. You can do this through the main page.setOr from AnqiCMS'stdkTag to get these values, then usewithPass them toheader.html.

    {# 在某个详情页模板中 #}
    {% tdk page_title with name="Title" siteName=true %}
    {% tdk page_keywords with name="Keywords" %}
    {% tdk page_description with name="Description" %}
    
    
    {% include "partial/header.html" with title=page_title keywords=page_keywords description=page_description %}
    
  2. Dynamic sidebar or ad space:The website sidebar usually displays popular articles, the latest products, or advertisements. You can define a generalpartial/sidebar.htmlThen, based on different page types (article detail page, product list page) throughwithPass differentcategory_idormodule_idTo dynamically load related content in the sidebar.

  3. Content formatting and display:The article content obtained from the AnqiCMS backend may contain original HTML, and you may need to perform some character truncation or image lazy loading before displaying.setYou can quickly process these logic inside the template, and then use the processed variables for the final display.