How to define and use variables (set, with) in AnQiCMS templates?

Calendar 👁️ 66

Mastery of AnQiCMS template: Unlock the magic of variables (deep analysis of set and with)

As an experienced website operations expert, I know that a flexible and efficient content management system is crucial for the success of a website.AnQiCMS with its concise and efficient architecture and support for Django template engine syntax, provides us with great convenience.In template development, mastering the definition and assignment of variables is undoubtedly the key to enhancing the flexibility and maintainability of the template.setandwith.

Basic of template variables: The core of data flow

In the AnQiCMS template world, variables are the bridges that carry and display dynamic content.They can be the article title, category name passed by the backend controller, or the temporary data we create for logical processing or local display.{{ 变量名 }}The form presented in the template, waiting to be rendered into the final HTML content. Understanding the principle of variables is the first step to mastering AnQiCMS templates.

In-depth analysis{% with %}Tag: The Elegant Choice of Local Scope

{% with %}Tags are a way to define temporary variables in AnQiCMS templates, their most significant feature isThe scope is strictly limited to its defined{% with %}to{% endwith %}block. This means that the variables you define here are only valid within the current code block, once outsideendwith, the variable will become invalid. This locality makeswithtags very suitable for handling short-lifetime, locally strong variable assignment scenarios.

Imagine that you might need to simplify the naming of a long variable within a small area of a complex template, or you might need to aggregate the results of multiple expressions into a variable that is easy to understand. At this time,withTags come in handy. Its syntax is very intuitive:

{% with variable_name = "变量值" %}
    <!-- 在这里使用 {{ variable_name }} -->
{% endwith %}

You can even define multiple variables in a tagwithsimultaneously, just separate them with spaces:

{% with greeting = "你好" username = "访客" %}
    <p>{{ greeting }},{{ username }}!欢迎来到我的网站。</p>
{% endwith %}

{% with %}A very classic example of the tag is配合{% include %}The tag. When you need to introduce a common template snippet (such as the page headerheader.html), and want to pass some specific parameters to this segment without polluting the global variables of the main template,withit can solve this problem perfectly. For example:

{# 主模板中 #}
{% include "partial/header.html" with title="AnQiCMS网站首页" keywords="内容管理,CMS,GoLang" only %}

and in thepartial/header.htmlIn the file, you can use it directly{{ title }}and{{ keywords }}Here.onlyThe keyword ensuresheader.htmlCan only be accessed throughwithThe variable is passed, and it will not inherit other variables from the main template, which helps to maintain the independence and reusability of template fragments.

Master{% set %}Tag: More flexible variable definition

Compared towithof locality,{% set %}Labels provide a wider variable scope. It is used in the current template file or current block (if it is in{% block %}Variables defined within this scope can be accessed throughout all code following the point of definition. This allowssetTags are especially powerful when you need to perform intermediate calculations, store loop results, or save data more permanently.

setThe syntax of tags is also very concise:

{% set variable_name = "变量值" %}

For example, you may need to calculate the total number of an item list, or format an article summary and use it multiple times:

{# 假设 archives 是一个文档列表 #}
{% set total_archives = archives|length %}
<p>本站共有 {{ total_archives }} 篇文章。</p>

{% set article_summary = article.Description|truncatechars:150 %}
<div class="summary">{{ article_summary }}</div>
<!-- 稍后在其他地方再次使用 -->
<p>了解更多:{{ article_summary }}</p>

setThe flexibility of the label also lies in its ability to capture the output of other labels. For example, you may want to assign the output result of a template label to a variable for subsequent processing:

{% set site_name_raw %} {% system with name="SiteName" %} {% endset %}
<p>网站名称是:{{ site_name_raw|trim }}</p>

Please note,setVariables defined in different contexts (such asforwithin a loop) may exhibit different lifecycles. Within aforloop, a variable defined insetA variable, which is reassigned at each iteration and retains the last value assigned to it at the end of the loop (if the loop is not empty).

setwithwithDifferences and choices

UnderstandingsetandwithThe core difference lies in theirScopeandDesign intention:

  • Scope (Scope):
    • {% with %}: Strictly limited towithtoendwithInside a block. It creates a temporary variable environment, where variables are visible inside and not outside.
    • {% set %}: It is visible within the current template file or current module block until the end of the template file or module block. It is more like defining a local variable.
  • Design intention:
    • {% with %}: It is more倾向于Temporary, local data bindingEspecially when towardsincludePassing parameters to template fragments, it can effectively isolate variables and avoid naming conflicts.
    • {% set %}: More suitablePerform data processing, store calculation results, or prepare data for subsequent logic in the current template file. When you need to reuse a processed value at multiple locations in the template,setIs a better choice.

In short, when your variable is only used in a small code snippet and you do not want it to affect other parts, choosewith. And when you need to refer to or process a variable multiple times within the larger scope of the current template,setit provides greater convenience.

Advanced: Using filters to process variables

AnQiCMS template engine also provides richFilter (Filters)They are powerful tools used to convert and format variable outputs. Whether it issetOrwithdefined variables, they can be passed through a pipeline symbol|Process with a filter, for example:

  • {{ article.Content|safe }}: Output HTML content safely without escaping.
  • {{ article.CreatedTime|stampToDate:"2006-01-02" }}: Format the timestamp to a date.
  • {{ product.Price|floatformat:2 }}: Keep the floating-point price to two decimal places.

These filters combined with variable definition tags can help us control the presentation of content more finely, thus enhancing the practicality and display effect of the template.

Summary

In AnQiCMS template development,{% set %}and{% with %}They are the two powerful tools we use to define and manage variables.withLabels with their strict local scope provide us with a clean, side-effect-free temporary variable handling solution, especially when introducing template fragments, andsetLabels operate within a broader scope, meeting the needs for data processing and result storage within the current template, making the template logic clearer.

As website operation experts, we should flexibly choose these two variable definition methods according to actual needs, combine them with powerful filter functions, and jointly create an efficient, easy to maintain and content-rich AnQiCMS website template.


Frequently Asked Questions (FAQ)

  1. Ask: What are the naming conventions for variables in AnQiCMS templates?Answer: AnQiCMS template recommends using camelCase naming convention, which means each word starts with an uppercase letter, for example{{ ArchiveTitle }}/{{ SiteName }}In addition, all variables are enclosed in double curly braces{{ }}are used to wrap the output, while logical control tags (such asset

Related articles

How to format timestamp display in AnQiCMS template?

As an experienced website operation expert, I am well aware that the timeliness and presentation of content are crucial to user experience.In an efficient content management system like AnQiCMS, even a seemingly simple date display contains operational wisdom to enhance the professionalism and readability of the website.Today, let's delve into how to beautifully transform the original timestamps into user-friendly date formats in the AnQiCMS template.

2025-11-07

What are the common filters supported by AnQiCMS for processing template data (such as string truncation, date formatting)?

In the Anqi CMS template world, data is not just raw text or numbers, they are the foundation of excellent website content.However, the original data often needs to be polished before it can present itself in a certain posture to the user.At this time, the template filter has become an indispensable helper to us.They are like a Swiss Army knife for data processing, capable of performing various transformations, formatting, and refining template variables, bringing new luster to the data and meeting all kinds of display needs.As an experienced website operation expert

2025-11-07

How to implement nested category display in AnQiCMS template

As an experienced website operations expert, I am well aware of the value of a flexible and efficient content management system for the success of a website.AnQiCMS (AnQiCMS) relies on its high-performance architecture based on the Go language and the Django-style template engine, bringing great convenience and infinite possibilities to content display.Today, let's delve into a very common requirement in actual operation: how to implement nested display of multi-level categories in AnQiCMS templates, making your website structure clearer and enhancing the user experience.

2025-11-07

How to reference the common header and footer files in AnQiCMS templates?

As an experienced website operations expert, I fully understand how important it is to maintain consistency in website structure and development efficiency in a content management system.Especially when using a highly efficient and flexible system like AnQiCMS, it is reasonable to refer to common header and footer files, which can not only greatly improve the maintenance efficiency of templates, but also ensure the unity of the entire site style.Today, let's delve into how to achieve this goal in AnQiCMS templates.AnQiCMS with its high-performance architecture based on Go language and Django-style template syntax

2025-11-07

How to generate random text for testing in the AnQiCMS template?

As an experienced website operations expert, I am well aware that during the website development and content testing stage, it is often difficult to cook without the necessary ingredients - lacking real content to fill the page, in order to verify design, layout and function.Especially for operators and developers who use powerful and flexible content management systems like AnQiCMS (AnQiCMS), efficiently simulating content is the key to improving work efficiency.

2025-11-07

Where should the AnQiCMS template files be placed?

## Unveiling the Home of AnQiCMS Templates: Clear Guidance Helps You Customize Easily As an experienced website operations expert, I am well aware of the importance of a flexible and efficient content management system for businesses.AnQiCMS is an excellent platform developed based on the Go language, which not only wins the favor of many users with its high performance and high concurrency features, but also provides great convenience in customization.For operators and developers who want to fully utilize their customization potential and build personalized websites, clearly defining the storage directory of AnQiCMS template files is the first step towards success.

2025-11-07

How to define an AnQiCMS template configuration file (config.)?

As an experienced website operations expert, I fully understand the importance of a flexible and powerful content management system for enterprises.AnQiCMS is an excellent platform committed to providing efficient and customizable solutions.In the template ecosystem of AnQiCMS, a seemingly insignificant but powerful file - `config.`, plays a crucial role.It not only defines the basic attributes of the template, but also profoundly affects the behavior and performance of the template in the system.

2025-11-07

How does the AnQiCMS template support adaptive, code adaptation, and PC+mobile mode?

## AnQiCMS template: How to ride the multi-end content display with wisdom and flexibility?In today's fast-paced digital world, it is common for users to access websites through various devices.As experienced website operators, we know that whether a website can provide a smooth and high-quality experience on PCs, tablets, mobile phones, and other terminals is directly related to user retention and business conversion.

2025-11-07