How to define and display temporary variables in the template?

Calendar 👁️ 56

In Anqi CMS template development, mastering how to define and display temporary variables within the template is a very practical skill.It can help us handle data more flexibly, optimize template structures, and write simpler and more efficient code.Temporary variables are like the 'small tags' you grab on the fly when making a page, used to temporarily store some data for later use.

Why do we need temporary variables?

Imagine such a scenario: you might need to get a value from some label, then process this value in a series of operations (such as string truncation, time formatting), and finally use this processed result multiple times in different locations on the page.If you do not have a temporary variable, you may need to repeat these processes at each usage, which not only makes the code long-winded but also reduces maintainability.The introduction of temporary variables is precisely to solve such problems, making data processing and display more centralized and efficient.

The AnQi CMS template engine supports syntax similar to the Django template engine, providing an intuitive way to define and use these temporary variables.

How to define temporary variables in a template?

In AnQi CMS templates, there are mainly two ways to define temporary variables:setTags andwith.

1. UsesetThe tag defines variables

setThe tag is the most direct and commonly used method, which allows you to declare a new variable at any position in the template and assign a value to it.This variable is available in the current template file it is defined in, including within the block it is in.

Basic syntax:

{% set 变量名 = 值 %}

Here, 'value' can be a direct string, number, boolean, or even another variable, the output of a label, or even data processed through a filter.

Example:Assuming we need to get the title of the current document and store it in a variable namedpageTitle:

{# 获取当前文档的标题,并存储到 pageTitle 变量 #}
{% set pageTitle = archive.Title %}

{# 进一步处理标题,例如截取前10个字符,存储到 shortTitle #}
{% set shortTitle = pageTitle|truncatechars:10 %}

<title>{{ shortTitle }} - {% system with name="SiteName" %}</title>
<h1>{{ pageTitle }}</h1>

In this example, we first assignarchive.TitleAssign topageTitletopageTitleand perform a slicing operation, assigning the result toshortTitleThus,pageTitleandshortTitleThis can be reused anywhere in the subsequent template.

2. UsewithThe tag defines variables

withThe tag is used to define one or more temporary variables within a specific code block.setThe tag is different,withThe variable defined by the tag is only valid within{% with %}and{% endwith %}Scope is limited within, and its scope is localized. This is very useful for scenarios where temporary variables are needed but it is not desired to pollute the global variable list, especially when used in conjunctionincludewith the tag.

Basic syntax:

{% with 变量名1=值1 变量名2=值2 %}
    {# 在这里使用这些变量 #}
{% endwith %}

Example:Suppose you need to introduce a common page header templateheader.htmlAnd you want to pass some specific variables to this header:

{# 在 with 块内部定义两个变量 title 和 keywords #}
{% with title="安企CMS模板技巧" keywords="临时变量,模板开发,AnQiCMS" %}
    <head>
        <title>{{ title }}</title>
        <meta name="keywords" content="{{ keywords }}">
    </head>
    {# 或者将这些变量传递给一个 include 模板 #}
    {% include "partial/header.html" with title=title keywords=keywords %}
{% endwith %}

{# 在 with 块外部,title 和 keywords 变量不再可用 #}

BywithLabels, we can clearly define the scope of variables, avoid name conflicts, and improve the readability and modularization of the template. When used withincludelabels, withLabels can effectively manage data passed from the parent template to the child template.

How to display temporary variables?

Once a temporary variable is defined, displaying them is very simple. The Anqi CMS template engine uses double curly braces.{{ 变量名 }}syntax to output the value of the variable.

Example:Continue with the above example, displayingpageTitleandshortTitle:

{% set pageTitle = archive.Title %}
{% set shortTitle = pageTitle|truncatechars:10 %}

<!-- 在页面的任何地方显示 -->
<p>完整标题:{{ pageTitle }}</p>
<p>精简标题:{{ shortTitle }}</p>

If your temporary variable is a complex data structure, such as an object or an array (in Go it could be a struct or a slice), you can use a dot..Access its properties or elements.

Example:Suppose you defined a temporary variableuserInfoIt containsNameandEmailattribute:

{% set userInfo = {Name: "张三", Email: "[email protected]"} %}
<p>用户名:{{ userInfo.Name }}</p>
<p>联系邮箱:{{ userInfo.Email }}</p>

This is very useful for the scenario where data is retrieved and stored from tags and then the internal properties need to be accessed.

Combine filter processing data

The power of temporary variables also lies in their seamless combination with Filters.The filter can perform various data processing on variables and assign the processed result to a new temporary variable.

Example:Get the website name from the system settings and convert it to lowercase:

{% set siteName = system.SiteName %}
{% set lowerCaseSiteName = siteName|lower %}

<p>原始网站名:{{ siteName }}</p>
<p>小写网站名:{{ lowerCaseSiteName }}</p>

You can even use filters directly when defining variables:

{% set formattedTime = stampToDate(archive.CreatedTime, "2006年01月02日 15:04") %}
<p>发布时间:{{ formattedTime }}</p>

Summary

Defining and displaying temporary variables in AnQi CMS templates is the key to improving template flexibility and code organization. Whether it issetused for global definition, or utilizingwithPass localization, it can help you better manage data streams, combined with powerful filters, it can easily realize various complex data processing and display needs.Reasonably utilize these techniques, and your security CMS website template will be more efficient, readable, and easy to maintain.


Frequently Asked Questions (FAQ)

1.setTags andwithWhat is the difference between defining a temporary variable with tags? setThe variable defined by the tag is available throughout the current template file and any included subtemplates (local to the scope of the current template file). AndwithThe variable defined by the tag is only valid within{% with %}and{% endwith %}Valid between blocks, the scope is local.withTags are commonly used forincludeTags pass parameters to limit the scope of variables, to avoid naming conflicts.

2. What types of data can a defined temporary variable store?Temporary variables can store a variety of data types, including but not limited to:

  • Basic types:String (string), integer (integer), float (float), boolean (boolean).
  • Composite type: Arrays/slices, objects/structs, and maps. You can access them using a dot..or brackets[]to access these composite type data members.

3. Can I use filters for the temporary variables I define?Of course you can. This is a very useful aspect of the temporary variable.You can assign the output of the tag to a temporary variable, then apply one or more filters to the variable, and then assign the processed result to another temporary variable (or display it directly). For example:{% set processed_text = my_variable|truncatechars:10|lower %}. This makes the data processing flow clearer and more controllable.

Related articles

How to conditionally display different content or styles within a loop?

In website content display, we often encounter the need to display different content or assign unique styles to elements according to the order of data cycles, specific attributes, or states.For example, odd and even rows in the list need different background colors, special markings for certain types of products, or when a field is empty, hide the corresponding area.With its flexible and powerful Django-like template engine, AnQi CMS makes these requirements simple and easy to implement.By cleverly combining loop tags (`{% for ... %}`) and conditional judgment tags (`{% if ... %}`)

2025-11-08

How to display the names and introduction information of different user groups?

Displaying different user group names and introduction information in AnQi CMS is an important part of website personalized operation and content distribution.Whether you want to display exclusive identification for VIP members or provide customized content for users with different permissions, Anqi CMS's flexible template tag system can help you easily achieve this. ### Understanding the Core Concepts of User Group Information To display the name and introduction of the user group, it is first necessary to clarify two key points: whether the user is logged in, and which user group the user belongs to. Safe CMS provides powerful template tags

2025-11-08

How to display detailed information of the currently logged-in user (such as username, avatar, VIP status)?

In Anqi CMS, displaying the detailed information of the currently logged-in user, such as username, avatar, and VIP status, is a key step to enhance user experience and build a personalized website.AnQi CMS with its flexible template engine allows us to easily implement these features.This article will introduce how to display this information on your website front-end. ## Retrieve basic information of the currently logged-in user The Anqi CMS template system provides the `userDetail` tag, which is the core tool for retrieving various information of the currently logged-in user.This tag can directly retrieve the user data of the current session

2025-11-08

How to configure and display thumbnails with different processing methods (such as cropping, scaling)?

##驾驭安企CMS缩略图:精细化的配置与灵活的展示,打造视觉冲击力 在网站运营中,图片无疑是吸引用户、提升内容质量的关键元素。While thumbnails, as the first visual touchpoint of website content, their display effect directly affects users' desire to click and the overall beauty of the page.AnQi CMS knows this and provides us with flexible thumbnail configuration and display capabilities, helping us easily manage and present high-quality image content.### Core Configuration

2025-11-08

How to reference and display common code snippets (such as header, footer) in AnQiCMS templates?

It is crucial to maintain consistency in page structure and code maintainability in website construction and content management.For a content management system like AnQiCMS, effectively referencing and managing common code snippets, such as the website header (Header) and footer (Footer), is the key to achieving this goal.Through AnQiCMS's flexible template mechanism, even users with little understanding of technical details can easily implement these features, thus building a website with clear structure and easy maintenance.###

2025-11-08

How to use the template inheritance mechanism to unify and display the website page structure?

When building a website, maintaining consistent page structure, improving development efficiency, and reducing maintenance costs are key to website operations.AnQiCMS (AnQiCMS) leverages its powerful functionality based on the Django template engine syntax to provide us with an efficient template inheritance mechanism, making it easy to unify and flexibly display the structure of web pages. ### The core concept of template inheritance: building the skeleton of a website Imagine that your website is like a house made up of different rooms. Each room (page) has its unique functions and content, but they share the same foundation

2025-11-08

How to dynamically display the current year or a specified date on a website?

In website operation, we often need to display some dynamic time information, such as the copyright year at the bottom of the website (such as “© 2023-Current Year”), the publication or update time of articles, or the deadline for specific events, etc.These dynamic dates not only maintain the timeliness of website information, but also improve user experience, and in some cases, are also beneficial for SEO. The AnQi CMS provides a series of flexible template tags that allow you to easily display the current year or a specified date dynamically at any location on the website.We will discuss in detail how to make use of these features.

2025-11-08

How does AnQi CMS display or hide specific content based on user group permissions?

In daily website operation, we often encounter such needs: some content is intended for everyone to see, while some is only open to specific members, or shows different information for users of different levels.AnQiCMS (AnQiCMS) provides powerful user group permission management features, allowing us to flexibly control the visibility of website content and achieve the 'thousand faces of content'. ### Why do you need to display or hide content by user group?Imagine you are running a website that offers a variety of services, including free basic articles and paid in-depth reports

2025-11-08