How to define and display temporary variables in Anqi CMS template for complex content layout?

Calendar 👁️ 60

In website content operation, we often encounter some scenarios where we need to flexibly display data and dynamically adjust the layout.It is sometimes difficult to list information simply to meet complex design requirements, at this point, if you can freely define and use some temporary variables in the template, it will greatly improve our efficiency and the expressiveness of the template.AnQiCMS (AnQiCMS) leverages its powerful backend developed in Go language and the template engine syntax similar to Django, providing us with flexible mechanisms for defining and managing temporary variables, making it possible to create exquisite and complex content layouts.

Define temporary variable:{% with %}with{% set %}

The Anqi CMS template engine provides two main tags to help us define and use temporary variables:{% with %}and{% set %}They each have their focus, understanding their differences can help us better plan the template structure.

{% with %}Label: An elegant choice for local scope.

{% with %}Tags are mainly used to define one or more temporary variables within a specific code block. These variables are only accessible{% with %}and{% endwith %}Valid between, once out of this range, they are no longer available. This feature of local scope makes{% with %}It is an ideal choice when creating independent, reusable components in a template or preparing data for a specific display area.

Imagine that you are defining some meta information for the page header, or preparing some temporary data for a component.{% with %}It can be put to use. It can not only define simple strings or numbers, but also pass more complex objects.

For example, if you want to pass some customized titles and descriptions to an included file (such as an article card component):

{% with cardTitle="最新公告", cardDescription="查看我们最近发布的重要通知!" %}
    <div class="info-card">
        <h3>{{ cardTitle }}</h3>
        <p>{{ cardDescription }}</p>
    </div>
{% endwith %}
{# 在这里,cardTitle 和 cardDescription 变量已经失效 #}

More commonly, {% with %}with{% include %}Label combination is used to pass specific data to the included template without polluting the global context, greatly enhancing the reusability of template components:

{# partial/article_summary.html #}
<div class="article-summary">
    <h4><a href="{{ summary_article.Link }}">{{ summary_article.Title }}</a></h4>
    <p>发布日期:{{ summary_date }}</p>
    <p>{{ summary_article.Description|truncatechars:120 }}</p>
</div>

{# 在主模板中调用 #}
{% archiveList latestArticles with type="list" limit="3" %}
    {% for article in latestArticles %}
        {% include "partial/article_summary.html" with summary_article=article summary_date=stampToDate(article.CreatedTime, "2006-01-02") %}
    {% endfor %}
{% endarchiveList %}

In this example,summary_articleandsummary_dateare inincludethrough the statementwithtemporarily defined variables, which are onlypartial/article_summary.htmlvalid within this local template.

{% set %}Label: Flexible assignment and dynamic calculation

Compared with that,{% set %}Labels allow us to refer to the current template file or block (such as{% block %}Within parentheses, you define and reassign variables. Their scope is wider, from the point of definition until the end of the template or the relevantblockend.{% set %}It is especially powerful when it comes to performing some calculations, data conversion, or accumulating results in a loop.

Suppose we need to calculate the total price of a list, or display a string after multiple steps processing:

{% set greeting = "欢迎光临安企CMS" %}
<p>{{ greeting }}</p>

{% set currentYear = "2024" %}
{% set nextYear = currentYear|add:1 %} {# 使用 add 过滤器进行数字相加 #}
<p>今年是 {{ currentYear }},明年是 {{ nextYear }}。</p>

{# 在循环中进行累加计算 #}
{% set totalOrders = 0 %}
{% archiveList recentOrders with type="list" limit="5" %}
    {% for order in recentOrders %}
        {% set totalOrders = totalOrders|add:1 %} {# 每次循环 totalOrders 增加1 #}
        <p>订单号:{{ order.Id }}</p>
    {% endfor %}
{% endarchiveList %}
<p>您最近有 {{ totalOrders }} 笔订单。</p>

{% set %}Its flexibility makes it the preferred choice for handling dynamic data logic within templates.

Practice Application: Building Complex Content Layout

Mastered{% with %}and{% set %}By using this method, we can achieve more complex and exquisite layouts in Anqi CMS.

1. Dynamic Content Display and Conditional Judgment

In content layout, we often need to display or hide specific content blocks based on certain conditions. Through{% set %}Preprocess the data, then combine{% if %}Tagging for judgment can make the page more intelligent.

For example, judge whether to display the 'new' mark according to the publication time of the article:

{% archiveDetail currentArticle with name="Id" %} {# 获取当前文章对象 #}
{% set publishTimestamp = currentArticle.CreatedTime %}
{% set twentyFourHoursAgo = now()|add:(-24*60*60) %} {# 假设 now() 返回当前时间戳,并减去24小时的秒数 #}

{% if publishTimestamp > twentyFourHoursAgo %}
    <span class="badge new-indicator">最新发布!</span>
{% endif %}

Here we define atwentyFourHoursAgoVariable, used to assist in judgment.

2. Data processing and formatting to enhance user experience.

Sometimes, the raw data obtained from the backend may not be suitable for direct display and needs to be formatted, truncated, or combined.{% set %}By using the rich Filters of AnQi CMS, these tasks can be completed.

For example, extract the article description, format the publish date, and combine it into a more user-friendly display text:

”`twig {% archiveDetail article with name=“Id” %} {# Get the current article object #} {% set

Related articles

How can AnQi CMS display a list of recommended articles related to the current article content?

In website operation, providing a list of recommended articles related to the current content is an important strategy to enhance user experience, extend user stay time, and optimize website internal links.AnQiCMS (AnQiCMS) knows this and provides flexible and powerful features to help you easily achieve this goal.### Core Function Analysis: Related Document Tag `archiveList` To display a list of recommended articles related to the current article content in AnQi CMS, you will mainly use a very key template tag—`archiveList`

2025-11-09

How to add captcha display to the comment feature of Anqi CMS to enhance security?

Maintaining a healthy, interactive website comment section is an indispensable part of content operation.However, comment sections often become hotbeds of spam and malicious attacks, which not only affects the quality of the website's content but also brings additional review burdens to website administrators.To effectively resist the interference of these automated programs, adding a captcha display to the comment feature of AnQi CMS is a simple and practical security enhancement measure.

2025-11-09

How to display a user's comment list in AnQi CMS and support multi-level replies and review status distinction?

The comment feature is an indispensable part of a website's content and user interaction, as it not only enlivens the atmosphere of the website but also provides valuable user feedback to the operator.Anq CMS fully understands its importance and provides a flexible and feature-rich comment system that allows website administrators to easily display and manage user comments, while also supporting multi-level replies and review status differentiation to ensure the interactivity and quality of website content. ### Overview of AnQi CMS Comment Function In AnQi CMS, to display the comment list of website content, it mainly relies on its powerful template tag system.

2025-11-09

How does the `urlize` filter in AnQi CMS automatically convert URLs in text to clickable links?

In the daily content creation and website operation, we often need to insert various links in articles, whether they point to external resources or refer to other content within the site.Manually converting these plain text URL addresses into clickable hyperlinks is undoubtedly a repetitive and error-prone task.Imagine if the amount of content on the website were massive, how much time and effort would it take to do this job?

2025-11-09

How does the `breadcrumb` tag in AnQi CMS generate and display flexible breadcrumb navigation?

When building a website, a clear and intuitive navigation system is crucial for user experience and search engine optimization (SEO).Breadcrumb navigation is a tool that can significantly improve website usability, clearly showing the user's current position on the site and providing convenient links to return to the previous level page.AnQi CMS knows this and provides a powerful and flexible `breadcrumb` tag.###

2025-11-09

How to display the language switch options and hreflang tags on Anqi CMS?

Today, providing multilingual support for websites has become a basic requirement for expanding the market and serving users in different regions.AnQiCMS (AnQiCMS) is fully aware of this need, integrating powerful multilingual functionality to allow website administrators to easily achieve content internationalization.This article will discuss in detail how to effectively display language switch options on AnQiCMS sites and correctly set the `hreflang` tag to optimize the internationalization recognition of search engines.Understanding AnQiCMS' multilingual capabilities AnQiCMS is an efficient

2025-11-09

How to implement the sorting display of article list by views (views desc) in AnQi CMS?

How to make a hot article on the website stand out quickly and attract more visitors' attention?This can effectively enhance user experience and is also the key to optimizing content strategy and guiding traffic.For users of AnQiCMS, it is a very practical and easy-to-operate feature to display article lists sorted by page views.The powerful template tag system of AnQi CMS allows you to easily display the most popular content on your website to users.### Core Feature Revelation: Utilize `archiveList`

2025-11-09

How to implement complex parameter filtering conditions for the dynamic display of the `archiveFilters` tag on the front end?

In website content operation, providing users with flexible and efficient filtering functions is an important factor in improving user experience and helping users quickly locate the information they need.AnQiCMS (AnQiCMS) knows this, making it easy to dynamically display complex parameter filtering conditions on the front end through its powerful template tag system, especially the `archiveFilters` tag.### Core Function and Implementation Principle The core function of the `archiveFilters` tag is to use the custom fields of the content model

2025-11-09