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

Calendar 👁️ 75

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.

Related articles

How to format a timestamp in AnqiCMS template to display a custom date and time format?

In AnqiCMS, managing website content, we often need to display the publication time, update time, or registration and login time of users, etc.These time information is usually stored in the database in the form of a timestamp, which is a series of numbers.If displayed directly on the website front end, these numbers are not intuitive and lack aesthetics.Fortunately, AnqiCMS provides very flexible template tags, allowing us to easily format these timestamps into the date and time display format we want.AnqiCMS template system

2025-11-09

How to iterate through data using the for loop tag in AnqiCMS templates and display list content on the front end?

In modern website construction, content lists are everywhere, whether it is article lists, product displays, user comments, or navigation menus, they cannot do without efficient organization and presentation of data.AnqiCMS as an enterprise-level content management system based on Go language, provides intuitive and powerful loop tags in template creation, allowing you to easily display various list content on the front page.

2025-11-09

How does the AnqiCMS template use if/else tags for conditional judgments to dynamically display different content?

In website content operation, we often need to flexibly display different content modules or styles based on different conditions to enhance user experience and page interactivity.AnqiCMS (AnqiCMS) provides powerful template tag features, among which the `if/else` conditional judgment tags are the core tools to achieve this goal.By it, we can easily make the website content come to life according to specific rules, no longer monotonous static display.### AnqiCMS template basic conditional judgment: `if`

2025-11-09

How to implement pagination navigation in AnqiCMS templates and customize the display of page numbers and style?

In a content management system, especially when a website carries a large amount of articles, products, or other list information, reasonable pagination navigation is the key to improving user experience and facilitating content browsing.It can not only help visitors quickly find the information they need, but also avoid the slow loading caused by too long single-page content, and it is also very beneficial for search engine optimization (SEO).AnqiCMS provides a powerful and flexible template tag set, allowing you to easily implement pagination functionality on your website and customize its display style and appearance as needed.### Enable pagination feature: Starting from the list tag At

2025-11-09

How to use AnqiCMS template include tag to introduce common code fragments and achieve page structure reuse?

In website content management, we often encounter situations where it is necessary to display the same content blocks, such as headers, footers, sidebars, or navigation menus, on multiple pages.If you copy and paste this code every time, it is not only inefficient, but also when you need to modify it, you have to face the繁琐 of repeated operations in multiple files.If this continues, the maintenance and updates of the website content will become extremely difficult, and inconsistencies in the experience may even occur.

2025-11-09

How to implement template inheritance using the extends tag in AnqiCMS templates to unify the visual style of the website?

In website operation, maintaining a consistent visual style is the key to brand image and user experience.Imagine if every page layout on your website was different, with navigation positions changing back and forth, users would feel confused and even lose interest.Fortunately, AnqiCMS provides a powerful and elegant way to solve this problem - that is through the `extends` tag in the template inheritance mechanism.AnqiCMS has adopted a template engine syntax similar to Django, making template development intuitive and efficient.

2025-11-09

How does AnqiCMS ensure that mathematical formulas and flowcharts can be displayed correctly on the front end after enabling the Markdown editor?

Today, with the increasing diversity of content creation, websites not only carry text and images, but also often need to display complex mathematical formulas or intuitive flowcharts.For those who use AnqiCMS, the good news is that the system has built-in powerful Markdown editor support, and with simple configuration, it can ensure that these professional contents are perfectly presented on the website front-end.Below, let's take a look at how to operate, making your website content richer and more professional.

2025-11-09

How to correctly display the independent content of each site on the front page of the multi-site management function of AnqiCMS?

In today's digital environment, many businesses and individuals need to manage multiple websites, whether it be different brand sites, product sub-sites, or multilingual versions for different markets.A system that can efficiently handle content across multiple sites is particularly important to meet such demands.The multi-site management feature of AnqiCMS is exactly for this purpose, it allows you to easily manage multiple websites from a single backend, while ensuring that each site can independently and correctly display its exclusive content on the front page.### The core advantages of AnqiCMS multi-site management First, let's understand

2025-11-09