How to define a temporary variable and perform assignment operations in a template?

Calendar 👁️ 53

Hello! As an experienced Anqi CMS website operator, I am very happy to give you a detailed explanation of how to define and assign temporary variables in Anqi CMS templates.This is crucial for achieving the flexibility, readability, and maintainability of templates, and it helps us organize and display website content more efficiently.

In the AnQi CMS template system, we often encounter scenarios where it is necessary to store data, calculate results, or prepare content for specific components locally. To meet these needs, AnQi CMS provides a simple and powerful variable definition mechanism, mainly realized through two tags:withTags andset.

Flexible applicationwithTags define local variables

withTags are powerful tools used in Anqi CMS templates to pass temporary variables within specific code blocks or to included templates. Their main feature is the scope limitation in{% with %}and{% endwith %}Between this, it makes variable management clearer, able to effectively avoid naming conflicts, especially suitable for preparing data for complex components or specific display areas.

When you need to temporarily define one or more variables in a part of the template, you can usewithLabel. For example, assume you are designing an article detail page, and you need to define a title and some keywords for a specific sidebar module on the page, but these variables should not affect the other parts of the page.You can operate like this:

{% with sidebarTitle="热门推荐" sidebarKeywords="SEO优化,内容营销" %}
    <aside class="sidebar-module">
        <h2>{{ sidebarTitle }}</h2>
        <p>相关关键词:{{ sidebarKeywords }}</p>
        {# 这里可以放置使用 sidebarTitle 和 sidebarKeywords 的内容 #}
    </aside>
{% endwith %}

In this example,sidebarTitleandsidebarKeywordsThese two variables are only in{% with %}and{% endwith %}tags wrapped in<aside>The element is valid inside. Once outside this area, these variables will no longer be available, ensuring the locality and non-interference of the variables.

withAnother common and very practical scenario is to pass to the enclosed template (throughincludeLabeling the template fragment to pass data makes the template fragment more general. It can display different content according to the parameters passed. For example, you have a universal header templatepartials/header.htmlIt may be necessary to display page titles and highlighted navigation items. You can introduce and pass variables in the main template like this:

{% include "partials/header.html" with pageTitle="关于我们" activeNavItem="about" %}

and in thepartials/header.htmlYou can use it directly in the template.{{ pageTitle }}and{{ activeNavItem }}Render the corresponding content to achieve the reusability and dynamicization of the header template. You can pass multiple variables at one time, just separate them with spaces.withAfter that, separate them with spaces.key="value"And that's it.

UsesetThe tag defines a variable in the current template

withwithThe tag emphasizes local scope and parameter passing differences,setThe tag is used to define variables in the current template file, its scope starts from the point of definition and extends to the end of the current template, or in nestedblockTags within can be inherited and used by their child blocks. This makessetThe tag is very suitable for storing intermediate calculation results, temporary storage of values, or defining public variables for the entire template or most of its content.

Define a variable and assign it a value, the syntax is very intuitive:

{% set totalViews = archive.Views + 100 %}
<p>文章总阅读量:{{ totalViews }}</p>

In this example, we define a macro namedtotalViewsvariable, and set its value toarchive.Views(assuming this is the number of page views of an article retrieved from the backend) plus a fixed number.totalViewsThe variable can be called at any subsequent position in the current template.

setThe power of tags lies in their ability to store more complex results, such as the output of other template tags or processed data by filters. For example, if you need to format a timestamp and store the result for multiple uses, you can do it like this:

{% set publishTime = stampToDate(archive.CreatedTime, "2006年01月02日 15:04") %}
<p>发布于:{{ publishTime }}</p>
<p>本文更新于:{{ publishTime }}</p>

This way, you only need to calculate the formatting time once, and you can refer to it multiple times in the templatepublishTimeTo avoid repetitive code, improve template efficiency and maintainability. In addition,setLabels define variables that are defined in the parent template and are usually available in the child templates inheriting the parent template, which provides great convenience for building hierarchical template structures.

In summary,withTags andsetTags are effective ways to define temporary variables in Anqi CMS templates, each with its own focus:withApplicable to local scope and towardsincludePassing parameters to the template, andsetIt is more suitable to store and reuse variables in the current template and its sub-blocks.Understand and make good use of these two tags, which will help you build a more flexible, efficient, and easy-to-maintain secure CMS website template.


Frequently Asked Questions (FAQ)

Ask: Can I use a variable defined in a parent template and then use it in the child template that inherits it?setCan I define a variable in a parent template and then use it in the child template that inherits it?Answer: Yes, in most cases, you can use it in the parent template.{% set %}The defined variable can be used directly in the child template inheriting the parent template.This means that any value calculated or defined in the parent template can be conveniently accessed and rendered in the child template, thereby achieving data sharing and transmission.

Ask: If I use both at the same timewithandsetWhich one will take effect if the tag defines a variable with the same name?Answer: In{% with %}Inside the code block wrapped by the tag,withThe variable defined by the label takes precedence because it has a more local scope. Once it leaves{% with %}Block, if there is an existing one with the same namesetA variable, thensetThe variable will take effect again. It is recommended to use descriptive variable names to avoid potential confusion.

Can I usesetorwithtags to store other template tags such asarchiveDetailWould you like the output result of?Of course you can. This issetandwitha very useful aspect of tags. You can assign the result of any template tag or filter to a variable. For example,{% set articleTitle = archiveDetail with name="Title" %}The article title will be stored inarticleTitlea variable for easy use in templates. This greatly enhances the flexibility and maintainability of the template.

Related articles

How to format a timestamp from a database into a readable date and time string?

As an experienced CMS website operation personnel of AnQi, I know that the content of the website should not only be rich, but also presented in a user-friendly manner.Time information is an important part of the content, but the timestamps (Unix timestamps) stored in the database are often just a string of numbers, which can be confusing to display directly.Therefore, formatting these timestamps into easily readable date and time strings is a key step in enhancing user experience and increasing content readability.

2025-11-06

How to use a `for` loop to iterate over data and handle `empty` data situations?

As an experienced CMS website operations personnel, I fully understand the importance of content in attracting and retaining users.Dynamic, responsive website content display is the key to improving user experience, and effectively handling data sets, especially when the data may be empty, is a basic skill in operation work.AnQiCMS (AnQiCMS) powerful template engine provides us with flexible tools to achieve these goals, where the `for` loop tag and its `empty` block are our powerful assistants for content display.

2025-11-06

How does the Anqi CMS template support `if`, `elif`, `else` logical judgments?

In Anqi CMS template design, conditional logic judgment is an indispensable part for realizing dynamic content display and complex layout control.As a website operator, I am well aware that flexibly using `if`, `elif`, `else` and other logical judgment tags can allow us to present a wide variety of page content based on different data states or business requirements, thereby enhancing user experience and the interactivity of the website.The Anqi CMS template engine supports syntax similar to the Django template engine, which allows users familiar with other mainstream CMS template languages to quickly get started

2025-11-06

How to implement and display pagination navigation on list pages (such as article lists, search results)?

As an experienced CMS website operations personnel for an Internet security company, I know that the details of content presentation are crucial for user experience and website SEO.Page navigation is one of the fundamental and key components, which not only helps users efficiently browse a large amount of content, but also allows search engines to better crawl and index website information.Today, I will elaborate on how to elegantly display pagination navigation on the list page of AnQi CMS, such as article lists, search result pages, etc.### Overview of Pagination Mechanism in AnQi CMS Implementing pagination functionality in AnQi CMS is intuitive and efficient

2025-11-06

What are the different roles of the three auxiliary tags `include`, `extends`, and `macro` in template structure organization?

As an experienced CMS website operation personnel of AnQi, I am well aware of the importance of a clear and efficient template structure for content management and website maintenance.In AnQi CMS, the template engine provides various auxiliary tags to help us better organize and reuse template code, among which `include`, `extends`, and `macro` are the three great tools for building a flexible template architecture.They each have different responsibilities, but together they serve to enhance the maintainability and development efficiency of the template.### Modular content reuse

2025-11-06

How to use built-in filters (such as `truncatechars`, `upper`) to process and convert the data format of template variables?

As an experienced AnQiCMS website operation person, I am fully aware of the importance of content in attracting and retaining users.High-quality content not only requires careful creation, but also needs to be presented in an appropriate format and optimized to enhance user experience and readability.AnQi CMS, with its flexible Django template engine syntax, provides us with powerful built-in filter functions, allowing us to easily process and convert the data format of template variables.Next, I will give a detailed introduction on how to use the built-in filter of Anqi CMS

2025-11-06

What file extension should AnQiCMS template files use?

As an experienced AnQi CMS website operation personnel, I know that template files play a core role in building a flexible and efficient website.They not only carry the visual presentation of the website, but also serve as a bridge for content and user interaction.For Anqi CMS, understanding the composition and usage specifications of its template files is the foundation for efficient content management and website optimization.According to the official document of Anqi CMS, template files uniformly use the file extension `.html`.

2025-11-06

How should static resources (CSS/JS/images) be stored and referenced in the AnQiCMS template?

As a website manager who is deeply familiar with AnQiCMS operation, I know that proper management of website static resources is crucial for improving user experience and website performance.In AnQiCMS template development and maintenance, reasonably storing and referencing CSS, JavaScript, and images, etc., is the foundation for building an efficient and stable website.Below, I will elaborate on this key link.

2025-11-06