How to declare and use custom variables for temporary assignment in a template?

Calendar 👁️ 64

As an experienced security CMS website operator, I am well aware of the importance of using variables flexibly in the process of template development to improve content display efficiency and maintainability.In Anqi CMS, we can declare and use custom variables through a concise and clear syntax to temporarily assign data, thereby better organizing and presenting website content.

Variable declaration method in Anqi CMS template

In the Anqi CMS template system, based on its support for the Django template engine syntax, it provides two main ways for developers to declare custom variables and temporary assignments:{% with %}Tags and{% set %}Labels. These two methods have different focuses and can meet the needs of different template development. Understanding their differences and application scenarios is the key to efficient template customization.

Use{% with %}Temporarily assign the tag

{% with %}Tags are mainly used for assigning temporary variables in specific module blocks, their lifecycle is limited to the{% with %}and{% endwith %}code block between. This makeswithTags are very suitable for passing parameters to local template fragments (partial) or temporarily simplifying variable names in a local area.

Its basic syntax structure is:

{% with variable_name="value", another_variable=expression %}
    <!-- 在这里可以使用声明的变量 -->
    <p>标题:{{ variable_name }}</p>
    <p>另一个变量:{{ another_variable }}</p>
{% endwith %}
<!-- 在这里,声明的变量不再可用 -->

For example, when we need to introduce a common header (header) fragment in a template and want to pass a specific page title and keywords to this fragment,withTags are especially practical. Suppose we have apartial/header.htmltemplate file that needstitleandkeywordstwo variables to generate the page<title>and<meta name="keywords">tags. We can use them like thiswithTags:

{% with page_title="安企CMS自定义变量教程", page_keywords="安企CMS, 模板变量, 自定义赋值" %}
    {% include "partial/header.html" with title=page_title keywords=page_keywords only %}
{% endwith %}

<div class="main-content">
    <h1>{{ page_title }}</h1>
    <p>这里是页面的主要内容。</p>
</div>

In this example,page_titleandpage_keywordsvariables only if{% with %}and{% endwith %}Valid inside. Passedincludelabel'swithParameters, we pass these variables topartial/header.html.onlyThe keyword ensuresheader.htmlReceived only explicitly passed variables, and will not inherit all variables in the current template, thus avoiding potential variable conflicts.

Use{% set %}Declare local variables with the tag

Compared to{% with %}of block scope,{% set %}Tags allow a local variable to be declared in the current template context, whose scope usually spans the entire template file or at least the block in which it is declaredblockThis makessetTags are very convenient when you need to reference a value multiple times in a template file, or when you need to store calculation results.

setThe syntax of tags is more direct:

{% set variable_name = "要赋的值" %}
<!-- 或者使用其他变量或标签的结果 -->
{% set current_year = now "2006" %}
{% set first_archive_title = archives[0].Title %}

<p>当前年份:{{ current_year }}</p>
<p>第一篇文章标题:{{ first_archive_title }}</p>

For example, on a document list page, we may need to retrieve the title of the first article in the current document list and use it in a specific area of the page. UsingsetTags can avoid repeated access to array indices, improving the readability and conciseness of template code:

{% archiveList articles with type="list" limit="10" %}
    {% if articles %}
        {% set featured_title = articles[0].Title %}
        {% set featured_link = articles[0].Link %}

        <div class="featured-article">
            <h2><a href="{{ featured_link }}">{{ featured_title }}</a></h2>
            <p>这是我们精选的第一篇文章。</p>
        </div>

        <ul>
            {% for item in articles %}
                <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% endfor %}
        </ul>
    {% else %}
        <p>暂无文章内容。</p>
    {% endif %}
{% endarchiveList %}

Here, featured_titleandfeatured_linkIn{% archiveList %}Tags rendered out:if articlesDeclared within a block and used in the subsequent content of the block.

Using variables and output

No matter which one you use{% with %}Or{% set %}Declare variables, whose values can be accessed through double curly braces{{ variable_name }}The way to access and output in the template. The Anqi CMS template engine also supports applying filters (Filters) and performing arithmetic operations on these variables to achieve more rich data processing and display effects.

For example, you can apply a string variable totruncatecharsA filter to truncate its length, or perform arithmetic operations such as addition, subtraction, multiplication, and division on numeric variables:

{% set long_description = "这是一段非常长的描述文本,可能需要被截断才能更好地显示在页面的有限空间内。" %}
<p>{{ long_description|truncatechars:30 }}</p>

{% set price_a = 100 %}
{% set price_b = 50 %}
<p>总价格:{{ price_a + price_b }}</p>

Application scenarios in practice

Custom variables have a wide range of applications in AnQi CMS template development, including but not limited to:

  • Pass data to a reusable component: Pass specific data or configuration items from the parent template through{% with %}pass to{% include %}to the child template, achieving high reusability of the component.
  • Simplify complex expressionsStore complex data paths or calculation results in a short variable to improve template readability and maintainability.
  • Temporary data storageIn a loop or conditional judgment, temporarily store an intermediate result for subsequent logic.
  • Dynamic content adjustment:According to the user's permissions or configuration, dynamically assign values and adjust display content, such as displaying different greetings or buttons.

Through proficiency{% with %}and{% set %}These variable declaration methods allow you to build secure CMS website templates more flexibly and efficiently, achieving complex and dynamic content display requirements.

Frequently Asked Questions (FAQ)

1.{% with %}and{% set %}What are the main differences in scope?

{% with %}Variables declared with tags are only in their{% with %}and{% endwith %}valid within the code block, it is mainly used to pass temporary data to local template fragments or to simplify variable names in specific code blocks.{% set %}The variable declared by the tag usually throughout the current template file (or the nearest one that declared it)blockBlocks can be accessed anywhere, its scope is wider, suitable for storing values or calculation results that need to be used in multiple places in the template.

2. Can the declared variable be used directly in other template files?

Accessed directly in other template files.{% with %}or{% set %}The declared variable is not allowed. The scope of the variable is local. If you need to pass the variable to another template file (for example, by{% include %}Introducing the child template), you need to explicitly pass through{% include "path/to/template.html" with variable_name=your_variable %}Pass it in this way. For{% set %}Declared variables, if you declare them in the parent template and then use them in the child template{% include %}Reference this sub-template, the sub-template can inherit the environment of the parent template unless youincludeused in theonlykeywords.

3. How to{% set %}use the result of other tags for assignment?

You can{% set %}Combine the output or variable of other tags with filters to assign values. For example, toarchiveListAssign the title of the first article obtained by the tag to a variable, you can do it like this:

{% archiveList articles with type="list" limit="1 %}
    {% if articles %}
        {% set first_article_title = articles[0].Title %}
        <p>第一篇文章的标题是:{{ first_article_title }}</p>
    {% endif %}
{% endarchiveList %}

You can also combine filters:

{% set raw_text = "Hello world! This is a test." %}
{% set truncated_text = raw_text|truncatechars:15 %}
<p>{{ truncated_text }}</p>

Related articles

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

As an experienced CMS website operation staff member, I fully understand that the details of content presentation are crucial for user experience.The accurate and clear display of time information not only helps users quickly understand the publication or update time of the content, but also indirectly affects the professionalism and credibility of the website.In Anqi CMS, we have a highly efficient and flexible mechanism that can convert timestamp data stored in the background into user-friendly date and time strings.### Timestamp formatting feature in AnQi CMS In AnQi CMS, date and time data are usually stored internally in the form of timestamps

2025-11-06

How to traverse an array or list and output each item on the page?

In AnQi CMS template development, effectively traversing and outputting arrays or lists is a core skill for building dynamic and rich content pages.As a senior security CMS operator, I know the importance of flexibly using template tags for content presentation.The Anqi CMS adopts a syntax similar to the Django template engine, making content looping and conditional judgments intuitive and powerful.

2025-11-06

How to use if-else logic in a template to control the display of content?

In Anqi CMS template creation, flexible control of content display is the key to improving user experience and meeting diverse business needs.As an experienced website operator, I am well aware of the importance of dynamic content presentation.The AnQi CMS adopts a syntax similar to the Django template engine, which allows content operators to implement conditional judgments in templates in a straightforward manner, thereby precisely controlling which content is visible to users at what time and place.The template syntax design of AnQi CMS makes it easy for developers and content operators to get started.

2025-11-06

How to customize the display of TDK (Title, Keywords, Description) content on a page?

As a senior AnQiCMS website operations personnel, I fully understand the core role of TDK (Title, Keywords, Description) in website search engine optimization (SEO).They are not only the key for search engines to understand the content of a page, but also important factors to attract users to click.In Anqi CMS, the configuration and custom display of TDK have high flexibility, which can meet the fine-grained optimization needs of different pages.

2025-11-06

How to split a template into multiple reusable parts (such as header, footer)?

As a practitioner who is deeply familiar with the operation of AnQiCMS, I know that content quality and website efficiency are the core of attracting and retaining users.In daily operation, we must not only pay attention to the content itself, but also ensure the efficiency and maintainability of the website structure.The modular decomposition of templates is the key technology to achieve this goal. Aqie CMS provides a powerful and flexible template mechanism that allows us to easily decompose website templates into smaller, more manageable reusable parts, such as headers, footers, sidebars, etc.

2025-11-06

How to implement lazy loading of images in article content?

Implementing the lazy loading of images in article content in AnQi CMS is a key link in improving website performance and user experience.As a website operator, I know full well the importance of loading speed for search engine rankings and user retention, and images, as an important part of web content, are often the main factors causing web pages to become bulky and slow to load.

2025-11-06

How to display the custom parameter fields of an article on the article detail page?

As an experienced CMS website operation personnel of an enterprise, I know that the standard fields often cannot meet the growing personalized needs of the website.The introduction of custom parameter fields has provided us with great flexibility, allowing us to add various unique attributes to articles based on different content models, thereby enriching the content dimensions and enhancing user experience.This article will detail how to effectively display the custom parameter fields of an article on the AnQi CMS article detail page.

2025-11-06

How to get and display the detailed information of a specified Tag label (name, description)?

As an operator of the AnQiCMS website deeply engaged in content operation, I fully understand the importance of tags in content organization and user experience.Tags can not only help readers quickly find the content they are interested in, but are also the key elements for optimizing website structure and improving SEO performance.Today, we will discuss in detail how to obtain and display the detailed information of the specified Tag label in AnQiCMS, including its name and description.

2025-11-06