How to define a temporary variable in a template and use it to display content?

Calendar 👁️ 72

In Anqi CMS, when managing website content, we often find that using temporary variables flexibly in templates can make the code more concise, efficient, easy to understand, and maintain.The Anqi CMS template system has borrowed the syntax of the Django template engine, providing a straightforward way to define and use these temporary variables.

Temporary variables make the template more concise and efficient

Why do we need to define temporary variables in the template?Imagine if you need to display a piece of data that has been processed complexly at different positions on a page, such as the first image extracted from a list or a calculated result.If there are no temporary variables, you may need to repeat the same logic or expression at each usage, which not only makes the template code long-winded but also reduces the rendering efficiency of the page.

By defining temporary variables, we can store these values and reuse them in multiple places in the template, greatly enhancing the readability and maintainability of the code.This is like giving a shorthand for a complex concept when writing an article, and then using the shorthand throughout, which can keep the writing smooth and help the reader understand quickly.

The Anqi CMS template mainly provides two ways to define temporary variables:{% set %}and{% with %}They have different focuses and are suitable for different scenarios.

Use{% set %}Define variables easily

{% set %}It is the most commonly used and most direct way to define a temporary variable in Anqi CMS template. Its syntax is very simple:{% set 变量名 = 值 %}Once defined, the variable can be used in{% set %}Used within the current template scope after the label until the template is parsed.

You can assign various types of values to it, such as strings, numbers, even other tags or filter results.

For example, on the article detail page, we may need to refer to the first image of the article multiple times as a cover, or we may need to format the publication time of the article. At this point,{% set %}it comes in handy:

{# 假设 archive.Images 是一个图片链接的数组 #}
{% set firstImage = archive.Images[0] %}
{% set formattedTime = stampToDate(archive.CreatedTime, "2006年01月02日") %}

<div class="article-header">
    <img src="{{ firstImage }}" alt="{{ archive.Title }}">
    <h1>{{ archive.Title }}</h1>
    <p>发布时间:{{ formattedTime }}</p>
</div>

<div class="article-body">
    {# ... 文章内容 ... #}
    <p>文章封面图:<img src="{{ firstImage }}" alt=""></p>
    <p>更新日期:{{ formattedTime }}</p>
</div>

In this example,firstImageandformattedTimeDefined as a temporary variable, avoiding repetition.archive.Images[0]andstampToDate(...)Such an expression makes the code clearer and easier to understand.

Utilize{% with %}Building a local scope

Compared to{% set %}the visibility of the variable throughout the template,{% with %}Tags provide a more 'enveloping' way of defining variables. Its syntax is{% with var1="value1" var2="value2" %} ... {% endwith %}. The variables defined here are only{% with %}and{% endwith %}valid within this range, once outside this range, these variables no longer exist.

{% with %}this local scope feature makes it particularly useful in the following scenarios:

  1. Pass multiple variables to the template:When you use{% include %}When a tag includes a small template snippet,{% with %}It can help you clearly pass a group of local variables to this snippet without polluting the parent template's namespace.

    For example, we have apartial/header.htmlIt needs to display the website title and keywords:

    {# index.html #}
    {% with pageTitle="安企CMS官网 - 轻松建站" pageKeywords="安企CMS, Go语言CMS, 企业建站" %}
        {% include "partial/header.html" %}
    {% endwith %}
    
    {# partial/header.html #}
    <head>
        <title>{{ pageTitle }}</title>
        <meta name="keywords" content="{{ pageKeywords }}">
    </head>
    

    Thus,partial/header.htmlcan be used directlypageTitleandpageKeywordsand these variables will not affectindex.htmlthe naming of variables in other parts.

  2. Define a set of related variables within a code block:If you need to perform a series of complex calculations or data processing within a specific logical block, and generate multiple temporary values,{% with %}Encapsulate these temporary values in this block to maintain code cleanliness.

    {% with totalSales = product.Price * product.Quantity, discountRate = 0.1 %}
        <p>总销售额:{{ totalSales }}</p>
        <p>优惠金额:{{ totalSales * discountRate }}</p>
    {% endwith %}
    {# 在这里,totalSales 和 discountRate 就不再可用了 #}
    

Practical application scenarios and insights

  • Avoid repeated calls and calculations:When a piece of data (such as the query results of a tag) needs to be rendered multiple times in a template, it can be assigned to a temporary variable to avoid repeated query execution, which improves the page loading speed.
  • Enhance readability and maintainability:Break down complex expressions into several smaller temporary variables, which can make the template logic clear.When you need to modify a value, you only need to modify the line where the temporary variable is defined, rather than modifying it in all the places where it is used.
  • Optimize condition judgment:Sometimes, the condition may be a complex expression. We can first store the result of the expression in a temporary boolean variable, and then use this variable for the conditional judgment, in order to{% if %}The statement is clearer.

Mastered{% set %}and{% with %}These two ways of defining temporary variables will allow you to be more agile in the template development of Anq CMS.Using them reasonably can not only make your template code cleaner, but also present the website content to users more efficiently.


Frequently Asked Questions (FAQ)

1.{% set %}and{% with %}What is the core difference when defining temporary variables?

The main difference lies in their scope.{% set %}Variables defined once are visible and usable throughout the remaining part of the current template. And{% with %}are only accessible within{% with %}and{% endwith %}The code block within the tags is effective. Usually,{% set %}It is suitable for general variables that need to be reused in multiple places in the template, whereas{% with %}it is more suitable to provide context variables for specific local code blocks (such as{% include %}introduced fragments) to avoid variable name conflicts.

2. Can I use a temporary variable in the loop (for)?

Of course. In{% for %}In loops, defining temporary variables is a common operation, their scope is limited to the current loop iteration. For example, you can calculate and store the attribute of the current element in each loop iteration, or based on the loop counter (forloop.Counter) Generate some special values.

`twig {% for item in archives %}

{% set articleLink = item.Link %}
{% set displayTitle

Related articles

How to display the content, title, and image of a single page in a custom page?

In website operation, we often need to create unique display methods for specific content, such as designing a unique landing page for product features, service introductions, or company profiles.AnQiCMS (AnQiCMS) with its flexible content model and highly customizable features, makes everything very simple.Today, let's talk about how to easily display the content, title, and images of a custom page, making your website content more personalized.

2025-11-09

How to use breadcrumb navigation tags to display the current page path at the top of the page?

In website operation, a clear navigation path is crucial for user experience and search engine optimization.When a user is browsing deep pages on a website, a straightforward 'You are here' prompt can help them quickly locate and easily return to the parent directory.This is a kind of auxiliary navigation method, which we call breadcrumb navigation.AnQiCMS (AnQiCMS) is built-in with powerful breadcrumb navigation tags, allowing developers and content operators to easily display the current location path at the top of the page.What is breadcrumb navigation and why is it important?

2025-11-09

How to display a list of friendship links on the front page of the website?

In website operation, friendship links have always been an important means to enhance website authority, increase external traffic, and enhance user trust.If you are using AnQiCMS to manage your website and want to display a list of friend links on the frontend page, you will find that this process is surprisingly simple and efficient.AnQi CMS, with its simple design and powerful features, makes content management easy, and the display of friendship links is no exception.Next, let's take a look at how to display friend links in Anqi CMS.

2025-11-09

How to customize the display of Banner Carousel images on the website homepage?

In website operation, the homepage Banner carousel image is an important component to attract visitors' attention and convey core information.AnQiCMS (AnQiCMS) understands this need and provides a flexible and convenient way for you to easily customize and display these key visual elements on the homepage of your website. ### Prepare: Manage Your Banner Image in the Background First, we need to make sure that the images used for the carousel have been uploaded and properly managed.The AnQi CMS usually provides a special "Banner Management" area in the background

2025-11-09

How to truncate long text content in a template and add an ellipsis for display?

In website content operation, we often encounter scenarios where it is necessary to display long text, such as article abstracts, product descriptions, or user comments.If the complete content is displayed directly, it may cause the page to be long and disorganized, affecting the reading experience of the user.At this time, the long text is intelligently truncated and an ellipsis (...) is added at the end, making it an elegant and practical solution.AnQi CMS as a powerful content management system, its flexible template engine provides a variety of convenient ways to meet this need.### Efficient Core Tool for Extracting Long Text Content

2025-11-09

How to ensure that the template file uses UTF-8 encoding to avoid garbled Chinese content?

In website operation, the clear and accurate presentation of content is crucial.Especially when your website contains Chinese content, if you encounter a "garbled code" problem, it not only seriously affects the user experience, but may also damage the professional image of your website.For users of Anqi CMS, ensuring that all template files use the correct encoding, especially UTF-8, is the first step to avoid such problems and is also the most fundamental and critical guarantee.### Why is UTF-8 so important? UTF-8 is the full name of Unicode Transformation

2025-11-09

How to display a custom shutdown notice to visitors when the website is under maintenance?

As website operators, we always encounter situations where we need to maintain and upgrade the website, whether it is database optimization, system updates, or content adjustments. These operations sometimes require temporarily shutting down the website to avoid unexpected errors or incomplete content display during maintenance.However, simply displaying a "cannot open" error page on a website undoubtedly gives visitors a bad experience, and may even make search engines mistakenly believe that the website is permanently offline.AnQiCMS (AnQiCMS) fully understands this pain point and provides a graceful and flexible solution that allows you to maintain your website while it is closed for maintenance

2025-11-09

How to dynamically obtain and display the current year in the template?

In website operation, it is crucial to maintain the timeliness and accuracy of content, especially information like copyright year, which, if manually updated, is not only cumbersome but also prone to omission.Our company AnQi CMS provides a very convenient way to dynamically obtain and display the current year in templates, ensuring the latest information on the website.

2025-11-09