How to define and temporarily store variables in a template for easy content display and reuse?

Calendar 👁️ 74

When building a website, we often encounter situations where we need to repeatedly display certain information or flexibly adjust content according to different contexts.If hardcoding is done every time, not only is it inefficient, but it is also quite麻烦 to maintain later.AnQiCMS (AnQiCMS) understands this, its template system provides various flexible ways to define and temporarily store variables in templates, thus realizing convenient display and efficient reuse of content.

Why do you need to define and store variables in the template?

In simple terms, defining a variable is like giving a temporary name to data. There are many benefits to doing this:

  • to enhance readability:The complex expression or data path can be replaced with a simple variable name, making the template code easier to understand.
  • Enhance reusability:Once the data is stored in a variable, it can be referenced multiple times in the template at various locations, avoiding repetition.
  • Convenient for content adjustment:When you need to modify a value, you only need to update the variable definition, and all references to the variable will be automatically updated, greatly simplifying maintenance work.
  • Separation of logic and display:Although AnQiCMS templates emphasize simplicity, appropriate variable definitions help encapsulate part of the display logic, allowing the template to focus more on how to present content.

AnQiCMS's template engine supports syntax similar to Django and Blade, making variable definition and usage very intuitive.

The primary way to define and temporarily store variables in the template

In AnQiCMS templates, we mainly have two types of tags to define and store variables:{% set %}and{% with %}.

Use{% set %}Tags for local variable assignment

{% set %}The tag is the most direct and commonly used way to define a new variable in the current template file.It allows you to assign a value, the result of an expression, or the content of another variable to a new variable name.{% block %}The area is available.

For example, you might want to set a specific title for the current page, or calculate a value in advance:

{% set pageTitle = "我们的产品与服务" %}
{% set currentYear = now("2006") %}
{% set welcomeMessage = "欢迎来到 " ~ system.SiteName ~ "!" %}

<h1>{{ pageTitle }}</h1>
<p>&copy; {{ currentYear }} {{ welcomeMessage }}</p>

In this example,pageTitle/currentYearandwelcomeMessageAre temporary variables, their values are defined in the current template after which they can be directly accessed at subsequent locations by double curly braces{{ 变量名 }}For reference

Use{% with %}Label defines a scope variable

When you need to define a set of variables within a specific code block and you want the scope of these variables to be limited to this code block, {% with %}Tags are very practical. They provide an independent variable scope, which is very helpful for keeping the template code neat and avoiding variable conflicts.{% with %}Tags need to be associated with{% endwith %}Used in pairs.

Imagine you have a universal header template snippet that you want to pass some specific titles and keywords to:

{% with headerTitle="最新的技术动态" headerKeywords="科技新闻,前端开发,Go语言" %}
    {# 这里的变量 headerTitle 和 headerKeywords 只在 {% with %} 块内有效 #}
    <head>
        <title>{{ headerTitle }}</title>
        <meta name="keywords" content="{{ headerKeywords }}">
    </head>
{% endwith %}

{# 在 {% endwith %} 之后,headerTitle 和 headerKeywords 就不能直接访问了 #}

{% with %}Especially suitable for use with other tags, for example:{% include %}This will be explained in detail later.

How to display the content of a variable?

No matter what you use{% set %}Or{% with %}Define variables, the ultimate purpose is to display their content. In AnQiCMS templates, this is achieved through double curly braces{{ 变量名 }}in the form.

If the variable itself is a complex data structure, such as an article object or a contact information object, we can access its internal properties or fields using the 'dot' operator. For example, if the template context has a namedarchiveThe article object, you can get its title and content like this:

<h1>{{ archive.Title }}</h1>
<div class="article-content">{{ archive.Content|safe }}</div>

Here|safeis a filter that tells the template engine not toarchive.ContentEscape HTML, as article content usually contains HTML tags and needs to be displayed directly.

Use variables to implement content block reuse.

The power of variables lies in their combination with the content reuse mechanism, which makes your website template more flexible and maintainable.

By{% include %}Passing variables

In actual projects, we often break down reusable parts of the page, such as navigation, sidebar, or footer, into independent template files (also known as 'partial templates'). At this time,{% include %}the tag comes into play.

What is even better is that when passing through{% include %}By introducing these local templates, we can make use ofwithKeywords to pass specific variables to make these local templates more general:

Suppose you have a_sidebar.htmlThe local template needscurrentCategorya variable to highlight the current category:

{# 在 _sidebar.html 中 #}
<aside>
    <h3>分类列表</h3>
    <ul>
        {% for category in categories %}
            <li {% if category.Id == currentCategory.Id %}class="active"{% endif %}>
                <a href="{{ category.Link }}">{{ category.Title }}</a>
            </li>
        {% endfor %}
    </ul>
</aside>

Then, in the main template, you can introduce it and pass the variable like this:

{% include "_sidebar.html" with currentCategory=categoryDetail %}

HerecategoryDetailIs the current page category detail object. Afterwithtransmission,_sidebar.htmlyou can use it.currentCategoryThe variable is used to render content. If you only want to pass specific variables and do not want the local template to access all variables of the current main template, you can useonlyKeyword:

{% include "_sidebar.html" with currentCategory=categoryDetail only %}

Thus,_sidebar.htmlonly can accesscurrentCategoryThis variable, other variables cannot be accessed.

Use{% macro %}Create reusable functions with labels

For those that are more like functions, needing to accept parameters to generate content templates,{% macro %}Tags are an ideal choice.You can imagine it as a small tool in the template, each time you call it, give it different inputs (variables), and it can help you generate the corresponding results.This makes the code highly modular and highly reusable.

For example, you can define a macro for displaying product cards:

{# 在一个单独的 product_macros.html 文件中 #}
{% macro product_card(product) %}
    <div class="product-item">
        <a href="{{ product.Link }}">
            <img src="{{ product.Thumb }}" alt="{{ product.Title }}">
            <h3>{{ product.Title }}</h3>
            <p class="price">¥{{ product.Price }}</p>
        </a>
    </div>
{% endmacro %}

Then, in the place where you need to use the product card, first import this macro, and then pass the product data as if calling a function:

`twig {% import "product_macros.html" as products %} {# Import macros and alias #}

{% for item in archiveList %}
    {{ products.product_card(item) }} {# 调用宏

Related articles

How can AnQi CMS protect the copyright of original content through anti-crawling and watermark features when displayed?

On a day when digital content is increasingly abundant, the value of original content is self-evident, serving as the cornerstone for attracting users and building brand images on websites.However, the issues of content theft and malicious collection that follow also make countless creators and operators headache.Hardly written articles, carefully designed images, may be borrowed by others in a moment, even copied and pasted directly, which not only severely打击s the original enthusiasm, but also actually harms the intellectual property rights.For website operators, original content is the core competitiveness of the website.

2025-11-08

How to get and display the current year in a template for dynamic content such as copyright information?

When operating a website, we often need to display the current year in the footer copyright statement, for example, “© 2023 All Rights Reserved.”. With the passage of time, this year needs to be updated annually, and if manually modified, it is undoubtedly a repetitive and easily overlooked task.AnQi CMS fully considers this common demand and provides a very intuitive and powerful template tag that allows you to easily realize the dynamic display of years, keeping your website's copyright information always up to date.###

2025-11-08

How to retrieve and display the contact information configured on the website backend (such as phone number, address, social media links)?

It is crucial to display a company's contact information clearly and conveniently in website operations, as it not only enhances customer trust but also serves as a direct way for users to obtain services and consult.AnQiCMS (AnQiCMS) is a powerful content management system that provides intuitive backend configuration options and flexible template calling mechanisms, allowing you to easily manage and display this information.Next, we will explore how to configure and display your website's contact information in AnQiCMS, including phone number, address, social media links, and more.--- ## First Part

2025-11-08

How to create and display custom single-page content (such as About Us, Contact Information)?

In website operations, content such as 'About Us', 'Contact Information', and 'Privacy Policy' is usually displayed in the form of independent pages. This content is relatively fixed and plays an important role in the website structure.AnQiCMS (AnQiCMS) provides an intuitive and powerful set of features for creating and managing these custom single-page applications, allowing you to easily publish and update without writing code. ### Create Custom Single Page Content Creating a single page in Anqi CMS is a simple and direct process.Firstly, you need to log in to the back-end management interface. 1. **Enter the page management

2025-11-08

How to determine whether the current item is the first or last in a looped article list so that special styles can be displayed?

In website content management, it is often encountered that there is a need: we hope that the first or last element of the article list, product list, or other data list can have special styles, such as the first article title being particularly prominent, or the last product detail not having a bottom separator line.This not only helps to highlight the key points, but also makes the visual effect of the page more hierarchical.AnQiCMS (AnQiCMS) powerful template engine provides us with a simple and efficient way to meet these customization needs.In Anqi CMS template system, we usually use `{% for ...

2025-11-08

How can AnQi CMS automatically replace keywords to display article or product content?

In content operations, we often need to ensure that specific keywords in articles or product descriptions are consistent, even automatically associated with related pages, which is crucial for SEO optimization and improving user experience.But manually modifying one by one takes time and is prone to errors, especially when the content of the website is massive, it is also a huge challenge.Anqi CMS knows this, and therefore provides us with a very practical feature, that is, the automatic replacement and display of keywords in articles or product content.This feature can intelligently identify the keywords or phrases you preset and automatically replace them with the specified text or link

2025-11-08

How to display custom additional field content on the detail page?

One of the core strengths of AnQiCMS is its flexible content model feature.It allows us to add various unique custom fields to content based on different business scenarios, such as products, services, events, etc.These custom fields greatly enrich the expression of content, making our website content more professional and meet the needs.But with these additional fields, how can they be presented elegantly on the front-end detail page?

2025-11-08

How to implement multi-condition filtering on a product list or article list page and display the filtered results?

In a content management system, providing users with flexible multi-condition filtering functions is a key factor in improving website usability and user experience.Whether it is an e-commerce website product list or a content portal article classification page, users hope to quickly locate the content they are interested in.AnQiCMS (AnQiCMS) with its powerful content model and template tag system allows you to easily meet this requirement and intuitively display the filtered results. ### 1.Establishing the foundation: defining content models and custom fields All filtering functions rely on data.

2025-11-08