How to define temporary variables in templates to assist in content display logic?

Calendar 👁️ 64

When using AnQiCMS for website content management, the flexibility of templates is crucial for achieving diverse content display.At times, we not only need to output data directly, but also need to perform some temporary processing, calculation, or judgment based on business logic, at which point defining temporary variables in the template becomes particularly useful.This not only makes the template code more neat, but also avoids repeated retrieval or calculation of the same data, thereby improving rendering efficiency and maintainability.

The Anqi CMS template engine syntax is similar to the Django template engine, providing powerful variable definition and logical control capabilities, where temporary variables are mainly defined through{% with %}and{% set %}These two tags can be used. Understanding their usage and scope can help us better build complex and expressive website templates.

Use{% with %}Tag: Local scope temporary variable

{% with %}Tags are mainly used to temporarily define one or more variables within a specific block of a template. The variables created are only valid within the{% with %}and{% endwith %}blocks. A typical use case for it is to{% include %}Labeling the child template passes additional variables, and these variables may not be globally available or need to be calculated temporarily.

Syntax structure:

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

Or define multiple variables at the same time:

{% with var1 = value1 var2 = value2 %}
    <!-- 在这里使用 {{ var1 }} 和 {{ var2 }} -->
{% endwith %}

Actual application example:

Assume you have a public header template filepartial/header.htmlIn which a dynamically generated title and keywords need to be displayed, and this information may be different on each page. You can do this:

  1. Define and pass in the main template:

    {% set page_specific_title = "我们的产品详情" %}
    {% set page_specific_keywords = "产品,详情,安企CMS" %}
    
    {% with custom_title = page_specific_title custom_keywords = page_specific_keywords %}
        {% include "partial/header.html" with custom_title custom_keywords %}
    {% endwith %}
    
    <main>
        <!-- 页面主体内容 -->
    </main>
    
  2. Inpartial/header.htmlUsing:

    <head>
        <title>{{ custom_title }}</title>
        <meta name="keywords" content="{{ custom_keywords }}">
        <!-- 其他头部元素 -->
    </head>
    

    By{% with %}, you can ensurecustom_titleandcustom_keywordsThese two variables are only inheader.htmland its containing{% with %}Valid within the block, avoiding variable name conflicts and maintaining code modularity.

Moreover, you can also in{% with %}make some temporary logical judgments within the block, such as:

{% with is_new_product = (product.CreatedTime > (now|date:"U") - 86400) %} {# 假设判断是否为24小时内发布的新产品 #}
    {% if is_new_product %}
        <span class="badge new-product">新品上市!</span>
    {% endif %}
    <h3>{{ product.Title }}</h3>
{% endwith %}

Use{% set %}Label: Flexible statement within the current template

{% set %}Labels allow you to declare a variable in the current template file, and after the declaration, this variable can be used anywhere in the current template (including nested templates).{% block %}or{% for %}visited and used in a loop until the template rendering is finished. Its scope is broader{% with %}and is suitable for scenarios where multiple uses or complex calculations are needed within the current template.

Syntax structure:

{% set variable_name = "值" %}
<!-- 在当前模板的后续部分使用 {{ variable_name }} -->

Actual application example:

  1. Simplify complex expressions:When you need to extract a value multiple times from a deeply nested object, use{% set %}It can greatly simplify the code.

    {% set category_name = archive.Category.Title %}
    <p>所属分类:<a href="{{ archive.Category.Link }}">{{ category_name }}</a></p>
    <p>您正在浏览的文档位于 "{{ category_name }}" 分类下。</p>
    
  2. Store the filtered results:The AnQi CMS provides rich filters, if you need to perform multiple filtering operations on the same data and store the final results.{% set %}is the ideal choice.

    {% set brief_description = archive.Description|striptags|truncatechars:100 %}
    <p>{{ brief_description }} <a href="{{ archive.Link }}">查看更多</a></p>
    

    Here, we first removedDescriptionThe HTML tags were then truncated to the first 100 characters, and the processed result was assigned tobrief_description.

  3. Cumulative calculation is performed in the loop:If you are in a{% for %}In a loop, you need to perform cumulative calculations for some data,{% set %}which can help you achieve it.

    {% set total_price = 0 %}
    {% for item in cart.Items %}
        <p>{{ item.Name }} - 数量:{{ item.Quantity }} - 单价:{{ item.Price }}</p>
        {% set total_price = total_price|add:(item.Quantity * item.Price) %} {# 使用add过滤器进行数值累加 #}
    {% endfor %}
    <p>购物车总价:{{ total_price }}</p>
    

When should which be used?

Select{% with %}Or{% set %}It mainly depends on your need for variable scope:

  • Use{% with %}:When you only need to be ina specific code block.For example, a<div>complex logic within a tag, or when passing information to{% include %}a sub-template. This helps to maintain the locality of variables and avoid unnecessary global pollution.
  • Use{% set %}:When you need toWithin a broader scope of the current template fileUsed when a variable is needed, or when continuous calculations and data transformations are required. It provides a way to define and reuse complex values in templates.

In summary,{% with %}emphasize the 'temporariness' and 'locality' of variables, while{% set %}The variable focuses more on the 'declaration' and 'reusability' within the current template. Mastering these tags will make your Anqie CMS template development more efficient and organized.


Frequently Asked Questions (FAQ)

Q1:{% with %}and{% set %}What is the essential difference between defined variables?

A1:The main difference between them lies in the variableScope.{% with %}The defined variable is only valid in its own{% with %}to{% endwith %}block or when it is passed throughwithpass the parameter to{% include %}Valid in the child template, it belongs to the local scope. And{% set %}The defined variable can be used at any subsequent position in the current template file after it is declared, including within any loop or conditional judgment it is in, until the rendering of the current template file ends.

Q2: Can I use{% for %}Define in a loop{% set %}Do you want to add variables and accumulate operations?

A2:Of course you can.{% set %}Variables are very suitable for accumulating, counting, or performing other iterative data processing operations within loops. As shown in the example article, you can initialize a{% set total_price = 0 %}variable, and then use it within the loop body{% set total_price = total_price|add:item.price %}This way of accumulating.

Q3: If I define a temporary variable but it may not have a value (for example, an object property does not exist), will it cause an error? How should I handle it?

A3:The template engine of Anqi CMS usually does not report an error when accessing non-existent variables or object properties, but treats them as empty values (such as empty strings or zeros). However, for code robustness and to avoid unexpected displays, you can usedefaultordefault_if_noneThe filter sets a default value for it. For example:{% set username = user.Name|default:"匿名用户" %}So even ifuser.NameIf it does not exist, it will also display "Anonymous user".

Related articles

How to format a timestamp into a readable date and time format for display in AnQiCMS?

The website content is updated frequently, each article, product, or comment has its creation and update time point.However, these times are usually stored in the background in the form of a series of numbers, which is what we commonly call timestamps.It is not friendly to display these timestamps to visitors, we need to convert them into a clear date and time format.In AnQiCMS, formatting these timestamps into the date and time format we are accustomed to is actually very simple and intuitive.The system comes with a powerful template tag that can help us easily achieve this.###

2025-11-08

How to use if/for tags in a template to control the conditional display and looping display of content?

When building and operating a website, the dynamic display and flexible management of content are key to improving user experience and operational efficiency.AnQiCMS (AnQiCMS) understands this point, therefore its template engine provides powerful and intuitive conditional judgment (`if`) and loop traversal (`for`) tags, allowing you to easily control the display logic of content and achieve highly customized page layouts.The template syntax of AnQi CMS borrows the concise style of Django template engine, with a very low learning cost.By mastering these core tags

2025-11-08

How to apply AnQiCMS pagination feature to the pagination display of article lists or Tag document lists?

In website content management, whether it is to display a large number of articles, products, or documents under categories, an efficient and user-friendly pagination function is crucial.It not only allows users to easily browse a large amount of content, avoid the slow loading caused by long pages, but also helps search engines better crawl and index website information.AnQiCMS is well-versed in this, providing intuitive and powerful pagination functions in template tag design, making it effortless to implement pagination display in article lists or Tag document lists.Understanding how AnQiCMS implements pagination

2025-11-08

How to display the friend link list at the bottom of the AnQiCMS website?

In website operation, friendship links play an indispensable role.It is not only an effective way for websites to recommend and share traffic with each other, but also an important means to enhance the weight and visibility of websites in search engines.However, how to conveniently manage and display these links on a website is a practical problem faced by many website managers.AnQiCMS as a system focusing on enterprise-level content management and SEO optimization, provides an intuitive link function and a flexible template calling mechanism, making this process extremely simple.###

2025-11-08

How to reference the common template code snippets (such as header and footer) in AnQiCMS to unify the display of the page?

It is crucial to maintain a unified page style in website content operation to enhance user experience and maintenance efficiency.Imagine if your website had hundreds or even thousands of pages, and each page's header, footer, or sidebar needed to be manually modified, that would be an enormous project.Fortunately, AnQiCMS provides a powerful and flexible template mechanism that can help you easily refer to and manage common code snippets, ensuring the consistency of the website display.AnQiCMS's template system borrows the syntax of the Django template engine, making it easy to use and powerful.it passes `

2025-11-08

How to use the template inheritance feature of AnQiCMS to build a consistent page skeleton and display local content?

During the process of website construction and operation, how to efficiently manage page layout, ensure consistency in visual style, and be able to flexibly adjust local content is a challenge faced by many operators.AnQiCMS provides a powerful template inheritance function, which can help us cleverly solve these problems, realize the structural management of website pages and the flexible display of content.Understand the core concept of template inheritance Imagine that template inheritance is like a blueprint or master template in architectural design.We first design a universal page skeleton, which includes the shared elements of all web pages

2025-11-08

How does AnQiCMS use static caching technology to improve page loading speed and content display efficiency?

In today's fast-paced online world, the loading speed and display efficiency of websites have become key indicators of user experience and search engine rankings.A responsive website can not only effectively retain visitors but also stand out in fierce competition.AnQiCMS (AnQiCMS) understands this, providing strong support for users to achieve fast website access and efficient content presentation through its built-in static caching technology.Understand static caching: The core mechanism of website acceleration To understand how AnQi CMS works, you first need to understand what static caching is

2025-11-08

How to prevent AnQiCMS website content from being maliciously scraped and add watermarks to images?

In the digital age, the value of original content is self-evident; they are the core of attracting traffic, building brands, and improving SEO rankings for websites.However, the risk of malicious collection of content and theft of images is also increasing.This not only harms the original creators' labor成果, but may also cause the website's ranking in search engines to be damaged, affecting brand reputation.As a website operator, we naturally hope to effectively protect our digital assets.The Anqi CMS is an efficient and comprehensive content management system that has always given full consideration to the importance of content security from the beginning of its design

2025-11-08