How to define and use custom variables in AnQiCMS templates, such as the `{% with %}` tag?

Calendar 👁️ 64

In AnQi CMS template design, we often encounter scenarios where we need to temporarily store or pass data. To make the template code clearer, more readable, and powerful, AnQi CMS provides a mechanism for defining and using custom variables, of which the most commonly used is{% with %}Tags and{% set %}Labels. They can help us handle data flexibly in templates, avoiding redundant calculations or passing complex objects.

Understand the basics of variables in AnQiCMS templates.

In AnQiCMS template, data display is mainly achieved through double curly braces{{ 变量名 }}To implement. For example,{{ archive.Title }}It will display the title of the current article. And when we need to perform logical control (such as conditional judgment, loop) or define temporary variables within the template, we will use single curly braces and the percentage sign{% 标签名 %}. The introduction of custom variables is based on this mechanism.

{% with %} tag: The magic of temporary variables.

{% with %}The tag is used to temporarily define one or more variables within a specific code block in a template. These variables are only valid in this{% with %}and{% endwith %}Between valid, once out of this range, they will become invalid. This scope limitation, makes{% with %}Very suitable for local optimization or passing specific parameters to included template fragments.

Its basic usage is as follows:

{% with variable_name="值", another_variable="另一个值" %}
    <p>这个标题是:{{ variable_name }}</p>
    <p>另一个变量是:{{ another_variable }}</p>
{% endwith %}

{# 在 {% endwith %} 之外,variable_name 和 another_variable 将不再可用 #}

In practical applications,{% with %}The strength of a tag lies in its ability to{% include %}be used in conjunction with tags. Suppose we have a general header (header) template filepartial/header.htmlWe hope it can display the title and keywords of the current page, but this information may vary from page to page. At this time, we can introduce it byheader.htmlpassing through{% with %}Pass these dynamic data:

{# 当前页面模板,例如 index.html #}
{% with page_title="首页", page_keywords="AnQiCMS, 模板, 变量" %}
    {% include "partial/header.html" %}
{% endwith %}

{# partial/header.html 中的内容可能如下: #}
<head>
    <title>{{ page_title }} - 站点名称</title>
    <meta name="keywords" content="{{ page_keywords }}">
</head>

Furthermore,{% with %}Also supports usingonlyKeywords to limit the templates included can only access{% with %}Variables defined here, rather than accessing other variables in the parent template, which helps to reduce variable conflicts and improve the independence of the template:

{% with dynamic_image="/path/to/dynamic.jpg" only %}
    {% include "partial/image_gallery.html" %}
{% endwith %}

{# 此时 image_gallery.html 只能访问 dynamic_image,不能访问其他变量 #}

The {% set %} tag: a flexible local variable

with{% with %}different,{% set %}The tag is used to define variables in a larger scope of the current template. It does not{% with %}Such explicit code block limits, once defined, variables are available in{% set %}The template content after the tag until the template rendering ends. This makes{% set %}It is very convenient when you need to store calculation results, simplify complex expressions, or reuse a value in multiple places in a template.

{% set %}The basic syntax is very intuitive:

{% set variable_name = "要赋的值" %}
<p>我的名字是:{{ variable_name }}</p>

{% set calculated_value = 10 + 20 %}
<p>计算结果是:{{ calculated_value }}</p>

{# 你也可以将标签的输出赋值给变量,例如使用过滤器 #}
{% set truncated_description = archive.Description|truncatechars:100 %}
<p>{{ truncated_description }}</p>

For example, in a document list, we may need to dynamically adjust the display style based on the length of the article title. We can first use{% set %}Store the length of the title and then use this variable in conditional judgments:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
        {% set title_length = item.Title|length %}
        <li {% if title_length > 30 %}class="long-title"{% endif %}>
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            <p>标题长度:{{ title_length }}</p>
        </li>
    {% endfor %}
{% endarchiveList %}

{% set %}It is particularly useful when handling the filter chain. If you have a complex combination of filters, you can store intermediate results to improve code readability or for further processing later.

When to use which tag?

Select{% with %}Or{% set %}It mainly depends on the purpose and scope of the variable you define:

  • Use{% with %}When you need to pass a temporary variable to a small block in the template or to a{% include %}template fragment.{% with %}It is a better choice. It defines the variable's lifetime, which helps prevent variable pollution and improves the clarity of local code.
  • Use{% set %}When you need a variable to be accessed or reused in multiple places within the current template,{% set %}It is more suitable. It is usually used to store calculation results, simplify long expressions, or act as a marker for the local state of the entire page.

In general,{% with %}and{% set %}All are effective tools for defining custom variables in AnQiCMS templates.合理运用它们,可以大大提升模板代码的可维护性、灵活性和可读性,让你的AnQiCMS网站内容展示更加出色。

Frequently Asked Questions (FAQ)

Q1:{% with %}and{% set %}What are the core differences between defined variables?A: The core difference lies in the scope of variables.{% with %}Variables defined only in{% with %}and{% endwith %}are effective between code blocks, which is block scope. And{% set %}The variable is available throughout the rest of the template after it is defined, it is a template scope.

Q2: Can I use{% for %}use labels inside{% set %}Define a variable?A: Of course, in{% for %}use labels inside{% set %}A defined variable, its scope will start from the point of definition and end at the loop.Each time the loop iterates, this variable can be reassigned or updated, which is very useful for accumulating calculations or processing intermediate data within the loop.

Q3: Will it cause an error if I define a variable but do not use it in the template?A: In most cases, defining a variable in the AnQiCMS template but not using it in the template will not cause a runtime error.The template engine will simply ignore variables that are not referenced.However, for the clarity and maintainability of the code, it is recommended to define only those variables that are indeed needed.

Related articles

What is the difference between the `{{variable}}` and `{% tag %}` syntax in AnQiCMS templates?

When using Anqicms to build a website, templates are the key to dynamic content display.We often see two special syntax structures in template files: `{{variable}}` and `{% tag %}`.Although they are all related to the display and processing of data, they play different roles and have different usage methods.Understanding the difference between them is the first step in efficiently using the Anqi CMS template.

2025-11-08

How to get the associated document list based on Tag ID and how to paginate it for `tagDataList` tags?

In website content operation, effectively organizing and displaying related content is crucial for improving user experience and the SEO performance of the website.AnQiCMS (AnQiCMS) provides powerful tag features, where the `tagDataList` tag is the key tool to help us achieve this goal.It can flexibly retrieve all related document lists based on the specified tag ID, and easily achieve content pagination display by coordinating with other tags.

2025-11-08

How to use the `tagDetail` tag to get the detailed information of a Tag, such as description and link?

In AnQi CMS, tags (Tag) are an important tool for organizing content, improving SEO, and enhancing user experience.Sometimes, we need not only to list tags, but also to display detailed information about a specific tag on the page, such as its description, link, and even Logo.At this moment, the `tagDetail` tag comes into play, helping us easily obtain this data.

2025-11-08

How to call the Tag list of the specified document in AnQiCMS template?

In AnQiCMS, tagging content (Tag) is an effective way to enhance content organization and user experience.These tags not only help search engines better understand the page theme, but also guide users to discover more related content.When you need to display the Tag list associated with a specific document in a template, AnQiCMS provides an intuitive and powerful `tagList` tag to make this operation very simple.

2025-11-08

How does AnQiCMS's 'Full Site Content Replacement' feature efficiently handle content strategy adjustments?

Today, with the increasing refinement and diverse strategies of content operation, how to adjust website content efficiently and accurately is a challenge facing every website operator.When brand information is updated, external link adjustments, or SEO strategy iterations occur, manually modifying thousands of contents on the website one by one is not only time-consuming and labor-intensive, but also prone to errors.Fortunately, AnQiCMS provides an extremely powerful tool - the "Full Site Content Replacement" feature, which can help operators with amazing efficiency and accuracy to deal with various content updates and strategy adjustments, and become a "secret weapon" for content management strategy adjustments.###

2025-11-08

How to configure the pseudo-static rules in AnQiCMS to optimize URL structure and include categories, model aliases?

Building a clear, search engine-friendly URL structure in AnQiCMS is a very important aspect of website operation.By reasonably configuring the pseudo-static rules and cleverly integrating categories and model aliases, not only can it enhance the user experience, but it can also significantly optimize the website's SEO performance.AnQiCMS as a high-performance content management system provides flexible pseudo-static features, allowing us to easily achieve these goals.The importance of optimizing URL structure Imagine you visit a website and see this kind of link: `example

2025-11-08

How to configure a separate domain and database information for a new site in AnQiCMS multi-site management?

AnQiCMS with its efficient and flexible multi-site management function provides great convenience to users, especially in scenarios where independent sites need to be built for different brands, products, or services.When you want to configure a separate domain and database information for a new site, AnQiCMS provides a clear and practical management process.This not only helps to isolate and secure the data, but also allows each site to have more independent operation and optimization space.### Understand the value of independent configuration for multiple sites Before discussing the specific operations

2025-11-08

How to implement multi-language content switching and display in AnQiCMS template?

In today's digital world, your website may need to be global for users.AnQiCMS fully understands this requirement and provides powerful multilingual support functions, allowing you to easily build and manage multilingual websites and better serve users from different countries and regions.How to implement multi-language content switching and display in AnQiCMS templates?Let's explore step by step. ### Understanding the multi-language mechanism of AnQiCMS: Handling two types of 'languages' In AnQiCMS, we need to distinguish between two types of 'language' content

2025-11-08