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