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

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) }} {# 调用宏