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.