How to define and assign variables in a template to temporarily control the display logic of content?

Calendar 👁️ 66

In Anqi CMS template development, flexibly defining and assigning variables is the key to dynamic display of website content and personalized layout.By skillfully using variables, we can temporarily adjust the way content is presented, making the template not only able to carry basic data display but also able to present a rich and colorful display logic according to specific conditions.This article will deeply explore how to define and assign variables in AnQiCMS templates, as well as their actual application in controlling the logic of content display.

The Foundation of Template Variables: Understanding and Application

AnQiCMS's template engine adopts a syntax style similar to Django, which makes variable definition and usage intuitive and efficient. In the template, we use double curly braces{{变量名}}Output the value of the variable. These variables may be system predefined (such as the title of the current article){{archive.Title}}), or a data set obtained through a specific tag (such as the navigation list{{navs}}),It can also be temporarily defined in the template according to our needs.

Understanding the scope of variables is crucial: some variables are available throughout the template rendering cycle, while others are limited to specific code blocks.This scope difference gives variables great flexibility in controlling display logic.

Two ways to define variables: With and Set

In AnQiCMS templates, we mainly have two ways to define and assign variables, each with its focus, suitable for different scenarios.

1.{% with ... %}: Local scope temporary variable

{% with %}Tags are mainly used to temporarily define variables within specific code blocks in templates. Their feature is that the scope is strictly limited to{% with ... %}and{% endwith %}Between. This means that once you leave this code block, these variables are no longer valid.This design is very suitable for those who only need to adjust the display logic locally and do not want to pollute the global scope of variables.

Basic usage:

You can define a single variable:

{% with pageTitle="这是我的自定义页面标题" %}
    <h1>{{ pageTitle }}</h1>
{% endwith %}

You can also define multiple variables at once, separated by spaces, and each variable uses变量名="变量值"in the form of:

{% with pageTitle="我的产品页面" pageKeywords="产品,分类,详情" %}
    <head>
        <title>{{ pageTitle }}</title>
        <meta name="keywords" content="{{ pageKeywords }}">
    </head>
{% endwith %}

with{% include %}the combination of tags:

{% with %}tags with{% include %}When combined, tags can bring out powerful modular capabilities. When we need to introduce a common template fragment (such as a sidebar, header navigation, etc.), but also want this fragment to dynamically display different content based on the context of the current page,withIt comes in handy. ThroughwithWe can pass specific variables to the template that is being introduced, and these variables are only valid in the template fragments that are introduced.

For example, we have a general header filepartial/header.htmlIt contains a title. When it is introduced on different pages, we hope that its title will be different:

{# 在基础模板或页面模板中引入header #}
{% include "partial/header.html" with pageTitle="首页 - 我的网站" pageKeywords="网站首页,最新内容" %}

Inpartial/header.htmlIn the file, you can directly use these variables passed in:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ pageTitle }}</title>
    <meta name="keywords" content="{{ pageKeywords }}">
</head>
<body>
    {# 其他头部内容 #}
</body>
</html>

If you only want to letincludeThe template only uses the variables passed in, and does not inherit all the variables of the current template, and can bewiththen addonly:{% include "partial/header.html" with pageTitle="首页" only %}

2.{% set ... %}: More flexible local variable declaration

except{% with %},AnQiCMS also provides{% set %}Tag, which allows you to declare variables at any position in the current template. And withwithdifferent,setThe scope of the defined variable starts from the point of definition, up to the end of template rendering, or until it is reassigned. This provides greater flexibility for the dynamic adjustment of variables.

Basic usage:

{% set greeting = "欢迎来到AnQiCMS!" %}
<p>{{ greeting }}</p>

{# 你可以在后续代码中修改它的值 #}
{% set greeting = "祝您使用愉快!" %}
<p>{{ greeting }}</p>

{% set %}Especially suitable for scenarios where you want to accumulate, process, or reassign variables within loops or conditional judgments, and hope that these variables continue to take effect in subsequent code.

For example, in a product list, you may need to calculate the total price of the products or count the number of products that meet certain conditions:

{% set total_price = 0 %}
{% for product in products %}
    {% set total_price = total_price + product.Price %}
    {# 显示商品信息 #}
{% endfor %}
<p>商品总价:{{ total_price }}</p>

The core role of variables in display logic

Defining variables is just the first step, their real power lies in combining them with conditional judgments and loop structures to temporarily control the display logic of content.

1. Combine conditional judgment ({% if %}As needed to display content

Variables often act as{% if %}The judgment basis of tags, deciding whether a part of the page is displayed, or what kind of content is displayed.

For example, you can display different welcome messages based on the value of a variable:

{% set isLogin = true %} {# 这个变量可能来自后端传递的用户登录状态 #}

{% if isLogin %}
    <p>欢迎回来,尊敬的用户!</p>
{% else %}
    <p>请<a href="/login">登录</a>或<a href="/register">注册</a>。</p>
{% endif %}

This is very useful when displaying exclusive content for VIP users, displaying different operation buttons based on user permissions, or enabling/disabling certain functional modules according to backend configuration.

2. Combine loop traversal ({% for %}): Control list display

When processing list data, the combination of variables and{% for %}tags is indispensable. Although{% for %}It can already traverse data, but we can further control the logic of the loop through variables, such as changing the display style within the loop, or filtering data based on variable values.

Assuming you have a list of articles and you want to add a 'recommended' tag before some specific article titles:

{% set featured_article_ids = [101, 105, 112] %} {# 假设这些ID的文章是推荐文章 #}

{% for article in articles %}
    <li>
        {% if article.Id in featured_article_ids %}
            <span style="color: red;">[推荐]</span>
        {% endif %}
        <a href="{{ article.Link }}">{{ article.Title }}</a>
    </li>
{% endfor %}

here,featured_article_idsThis variable temporarily controls the display logic of the article list, giving certain articles additional visual emphasis.

3. Skillfully use filters (filters): Optimize variable values

Although filters do not define variables directly, they can process the values of variables and indirectly affect the display logic. For example, you can usetruncatecharsThe filter is used to limit the length of the article summary, ensuring a neat page layout:

{% for article in articles %}
    <p>{{ article.Description|truncatechars:100 }} <a href="{{ article.Link }}">查看更多</a></p>
{% endfor %}

here,truncatechars:100The filter handledarticle.Descriptiona variable to ensure that the output content does not exceed 100 characters, maintaining consistency in display.

Real-world scenario case: Bring variables to life

Imagine you are designing the homepage of a corporate website. With variables, you can easily achieve the following dynamic display requirements:

  • The display quantity of the home focus picture (Banner):You can define a variable{% set banner_limit = 5 %}, then use it when calling the tag of the Banner list:{% bannerList banners limit=banner_limit %}. This way, you only need to modifybanner_limitThe value can control the display quantity of the home page Banner without modifying the specific list label parameters.

  • Highlighting specific category content:On the homepage, you may want to display the latest articles under the "Company Announcement" category in a special style. You can define{% set notice_category_id = 7 %}, then loop through the news list to use{% if article.CategoryId == notice_category_id %}Add additional styles or identifiers.

  • Display different functions based on user permissions.If your website has a user group management feature, you can get the user group information of the currently logged-in user and store it in a variable, for example{% set currentUserGroup = user.GroupId %}. Then, in the template through{% if currentUserGroup == "VIP" %}To display the exclusive service entrance or discount information for VIP users.

Summary: An efficient tool for template development.

Master the definition and assignment of variables in AnQiCMS templates and combine them with conditional judgments, loops, and other control structures, which is the key to enhancing the flexibility and maintainability of the template. Whether it is through{% with %}To create local, temporary variables or to use{% set %}Perform a broader variable declaration and update, these techniques can help you build a highly dynamic website interface that responds to user needs. Reasonable

Related articles

What methods does AnQiCMS provide for template developers to debug variable output and structure type?

When developing templates in Anqi CMS, understanding and debugging variable output and data structure types is the key to improving efficiency.Although the AnQiCMS template engine (similar to Django or Blade syntax) is intuitive and easy to use, mastering some debugging techniques can make you twice as effective when encountering problems.We usually understand the variables and data structures in the template through the following ways. ### 1.

2025-11-09

How do user group management and VIP systems affect the access permissions and display of specific content?

How to allow different users to see different content on a website, even charging for some high-value content, is the key to enhancing the value of the website and achieving monetization.AnQiCMS provides powerful and flexible features in user group management and VIP system, helping us achieve refined content distribution and differentiated display. ### Understanding the Core Value of User Groups and VIP Systems In Anqi CMS, user group management is the foundation for building personalized content experiences.

2025-11-09

How to use the 'safe output' mechanism of AnQiCMS template to avoid HTML content from being escaped?

In website content management, we often need to display various text information on the page, including HTML content with specific formats or interactive effects.AnQiCMS (AnQiCMS) is a modern content management system that, by default, takes an important security measure when handling template rendering: automatically escaping HTML content.This mechanism is designed to prevent cross-site scripting (XSS) attacks and ensure website security.However, in certain specific scenarios, such as when we want to display formatted content edited by a rich text editor, or custom HTML code snippets

2025-11-09

How to ensure that the URL strings in the content are automatically converted into clickable hyperlinks?

In daily website content operations, we often need to include various links in articles or descriptions, whether they point to other pages within the site or external references.One of the key aspects of user experience is that these URL strings can be automatically turned into clickable hyperlinks, rather than a series of cold texts.AnQiCMS (AnQiCMS) fully understands this and provides a variety of flexible and efficient methods to help us ensure that URLs in the content can be intelligently converted into clickable hyperlinks.Next, we will discuss how to achieve this goal in AnQiCMS

2025-11-09

How to use the 'Remove logical tag line occupation' feature to clean up extra blank lines rendered by the template?

When using AnQi CMS to manage a website, we all hope that the page presented to the visitor is both beautiful and efficient.The page loading speed and the neatness of the source code not only affect the user experience, but also have a subtle but important impact on search engine optimization (SEO).You may have encountered such a situation in the process of template development: although the template code looks neat, there are always some unwanted blank lines in the rendered HTML source code.

2025-11-09

How does AnQi CMS support displaying multilingual switch links and hreflang tags in the front-end template?

Today, with the increasing trend of globalization, many websites need to provide services to users from different countries and regions.This means that the website must not only support content display in multiple languages but also ensure that search engines can correctly identify these different language versions, thereby enhancing the visibility in the international market.AnQiCMS as a practical content management system provides strong and flexible support in this aspect.

2025-11-09

How to conditionally display elements in a template based on whether the content contains specific keywords?

In website operation, we often hope that the content can be presented more intelligently to visitors.For example, if a technical article mentions a specific product, we may want to automatically display the product's recommendation information at the top or side of the article;If the product description contains the phrase 'Limited Edition', we would like to add an eye-catching 'Limited' badge next to the product image.This ability to conditionally display elements based on whether the content contains specific keywords can greatly enhance the user experience and operational efficiency of the website.AnQiCMS as an efficient and flexible content management system

2025-11-09

How to accurately截取string or HTML content and add an ellipsis to adapt to layout requirements?

In website content operation, we often encounter such needs: In order to keep the page layout neat and the reading experience smooth, it is necessary to truncate the long text (whether it is plain text or content containing HTML tags) and add an ellipsis at the end.AnQiCMS provides very practical template filters that can help us accurately complete this task while ensuring that the content display is both beautiful and does not destroy the HTML structure.### Understanding the extraction requirements and the solution of AnQiCMS Imagine, in an article list

2025-11-09