In the template development of AnQi CMS, defining and assigning variables flexibly is the key to dynamic display of website content and personalized layout.By cleverly using variables, we can temporarily adjust the presentation of content, making the template not only capable of carrying basic data display but also able to present a rich variety of display logic based on specific conditions.This article will delve into how to define and assign variables in AnQiCMS templates, as well as their actual application in controlling the display logic of content.

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{{变量名}}Print the value of the variable. These variables may be system predefined (such as the title of the current article{{archive.Title}}), or a dataset obtained through a specific tag (such as the navigation list{{navs}}),can also be temporary defined in the template according to the 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.It is this scope difference that 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 own focus and suitable for different scenarios.

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

{% with %}Tags are mainly used to temporarily define variables within specific code blocks in templates. Its feature is that the scope is strictly limited to{% with ... %}and{% endwith %}between.This means that once outside of 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, with each variable taking变量名="变量值"the form:

{% 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 combining labels, it can unleash powerful modular capabilities. When we need to introduce a common template fragment (such as sidebars, header navigation, etc.), but also hope that this fragment can dynamically display different content based on the context of the current page,withit comes in handy. Throughwith, we can pass specific variables to the templates that are included, and these variables are only valid in the included template fragments.

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

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

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

<!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 useincludetemplate to use only the variables passed, and not inherit all variables of the current template, you canwithAdded lateronly:{% 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 location in the current template. 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 variables need to be accumulated, processed, or reassigned inside loops or conditional judgments, and it is desired 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 according to a certain condition:

{% 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

Define variables as the first step, but their true power lies in combining them with conditional judgments and loop structures to temporarily control the display logic of content.

1. Combine with conditional judgments ({% if %}):On-demand content display

Variables are often used as{% if %}the judgment basis of tags, determining whether a certain part of the page is displayed or what 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 function modules according to backend configuration.

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

When processing list data, the combination of variables and{% for %}tags is indispensable. Although{% for %}It can traverse data itself, 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 the variable value.

If you have a list of articles and you want to add a 'Recommended' label 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. Smart Use of Filters (filters): Optimize variable values

Although filters do not directly define variables, they can process the values of variables, thereby indirectly affecting the display logic. For example, you can usetruncatecharsThe filter to limit the length of the article abstract to ensure a tidy page layout:

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

Here,truncatechars:100The filter has processedarticle.DescriptionThe variable to ensure that the output content does not exceed 100 characters, maintaining consistency in display.

Actual 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 needs:

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

  • Highlight specific category content:On the homepage, you might want to display the latest articles under the 'Company Announcements' category in a special style. You can define{% set notice_category_id = 7 %}Then, in the loop of news lists,{% if article.CategoryId == notice_category_id %}Add additional styles or identifiers.

  • Display different features based on user permissions:If your website has user group management functionality, you can retrieve 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,{% if currentUserGroup == "VIP" %}Show VIP user exclusive service entry or discount information.

Summary: The efficient tool for template development.

Mastering the definition and assignment of variables in AnQiCMS templates and combining them with control structures such as conditional judgments and loops is the key to enhancing the flexibility and maintainability of the template. Whether through{% with %}Create local, temporary variables, or use{% set %}Perform more extensive variable declarations and updates, these techniques can help you build highly dynamic, responsive website interfaces. Reasonable