As an experienced CMS website operation personnel for security, I am well aware of the importance of flexibly using variables in the template development process to improve the efficiency of content display and maintainability.In AnQi CMS, we can declare and use custom variables with concise and clear syntax to temporarily assign data, thus better organizing and presenting website content.

Variable declaration method in Anqi CMS template

In the template system of AnQi CMS, based on its support for Django template engine syntax, it provides two main ways for developers to declare custom variables and temporary assignments:{% with %}Tags and{% set %}Label. These two methods have different focuses and can meet various template development needs. Understanding their differences and application scenarios is the key to efficient template customization.

Use{% with %}Label is assigned temporarily

{% with %}Labels are mainly used for temporary variable assignment in specific module blocks, and their lifespan is limited to{% with %}and{% endwith %}code blocks.withThe label is very suitable for passing parameters to local template fragments (partial) or temporarily simplifying variable names within a local area.

Its basic syntax structure is:

{% with variable_name="value", another_variable=expression %}
    <!-- 在这里可以使用声明的变量 -->
    <p>标题:{{ variable_name }}</p>
    <p>另一个变量:{{ another_variable }}</p>
{% endwith %}
<!-- 在这里,声明的变量不再可用 -->

For example, when we need to include a generic header (header) fragment in a template and want to pass a specific page title and keywords to this fragment,withThe tag is particularly practical. Suppose we havepartial/header.htmla template file, it needstitleandkeywordstwo variables to generate the page.<title>and<meta name="keywords">We can use the tag like thiswithTags:

{% with page_title="安企CMS自定义变量教程", page_keywords="安企CMS, 模板变量, 自定义赋值" %}
    {% include "partial/header.html" with title=page_title keywords=page_keywords only %}
{% endwith %}

<div class="main-content">
    <h1>{{ page_title }}</h1>
    <p>这里是页面的主要内容。</p>
</div>

In this example,page_titleandpage_keywordsvariables only in{% with %}and{% endwith %}Block valid. ThroughincludeTagswithParameters, we passed these variables topartial/header.html.onlyKeywords ensureheader.htmlOnly receive the variables explicitly passed, and will not inherit all variables from the current template, thus avoiding potential variable conflicts.

Use{% set %}declare local variables in tags

Compared to{% with %}block scope,{% set %}The label allows a local variable to be declared in the current template context, whose scope usually spans the entire template file, or at least the block within which it is declared.blockThis makessetTags are very convenient when you need to refer to a value multiple times in a template file, or when you need to store calculation results.

setThe syntax of the tag is more direct:

{% set variable_name = "要赋的值" %}
<!-- 或者使用其他变量或标签的结果 -->
{% set current_year = now "2006" %}
{% set first_archive_title = archives[0].Title %}

<p>当前年份:{{ current_year }}</p>
<p>第一篇文章标题:{{ first_archive_title }}</p>

For example, in a document list page, we may need to get the title of the first article in the current document list and use it for a specific area of the page. UsingsetLabels can avoid repeated access to array indices, improving the readability and conciseness of template code:

{% archiveList articles with type="list" limit="10" %}
    {% if articles %}
        {% set featured_title = articles[0].Title %}
        {% set featured_link = articles[0].Link %}

        <div class="featured-article">
            <h2><a href="{{ featured_link }}">{{ featured_title }}</a></h2>
            <p>这是我们精选的第一篇文章。</p>
        </div>

        <ul>
            {% for item in articles %}
                <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% endfor %}
        </ul>
    {% else %}
        <p>暂无文章内容。</p>
    {% endif %}
{% endarchiveList %}

Here,featured_titleandfeatured_linkIn{% archiveList %}Rendered by labels:if articlesDeclared within a block and used in the subsequent content of that block.

The use of variables and output

No matter which one you use{% with %}Or{% set %}Declare a variable, its value can be accessed through double curly braces{{ variable_name }}The way to access and output in the template.The template engine of Anqi CMS also supports applying filters (Filters) and performing arithmetic operations to these variables, in order to achieve more rich data processing and display effects.

For example, you can apply to a string variabletruncatecharsThe filter to truncate its length, or perform arithmetic operations on numeric variables:

{% set long_description = "这是一段非常长的描述文本,可能需要被截断才能更好地显示在页面的有限空间内。" %}
<p>{{ long_description|truncatechars:30 }}</p>

{% set price_a = 100 %}
{% set price_b = 50 %}
<p>总价格:{{ price_a + price_b }}</p>

Actual application scenarios

Custom variables have a wide range of applications in the development of Anqi CMS templates, including but not limited to:

  • Pass data to a reusable component: Pass specific data or configuration items from the parent template to{% with %}Pass to{% include %}the child template to achieve high reusability of the component.
  • Simplify complex expressions:Store complex data paths or calculation results in a short variable to improve the readability and maintainability of templates.
  • Temporary data storageIn a loop or conditional judgment, temporarily store some intermediate result for subsequent logic use.
  • Dynamic content adjustmentEnglish: According to the user's permissions or configuration, dynamically assign and adjust display content, such as displaying different welcome messages or buttons.

By mastering{% with %}and{% set %}These two variable declaration methods will enable you to build safe CMS website templates more flexibly and efficiently, and meet the complex and dynamic content display needs.

Common Questions and Answers (FAQ)

1.{% with %}and{% set %}What are the main differences in scope?

{% with %}Variables declared with tags are only accessible in their{% with %}and{% endwith %}Between code blocks is valid, it is mainly used to pass temporary data to local template fragments or to temporarily simplify variable names within a specific code block.{% set %}The label declared variable usually exists throughout the entire current template file (or the nearest one that declares it)block块)中都可访问,它的作用域更广,适合存储需要在模板中多处使用的值或计算结果。

2. The declared variable can it be used directly in other template files?

Access through directly in other template files{% with %}or{% set %}The declared variable is not allowed. The scope of the variable is local. If you need to pass the variable to another template file (for example, through{% include %}Introducing a sub-template), you need to explicitly pass it by{% include "path/to/template.html" with variable_name=your_variable %}this method. For{% set %}variables declared, if you declare them in the parent template and then use them in the sub-template{% include %}Reference this sub-template, the sub-template can inherit the environment of the parent template unless you useincludeThe label used containsonlykeywords.

3. How to{% set %}other tags in the use to assign values?

You can in{% set %}The output or variable of other tags is combined with the filter and assigned a value in the label. For example, to assignarchiveListThe title of the first article obtained by the tag is assigned to a variable, you can do it like this:

{% archiveList articles with type="list" limit="1 %}
    {% if articles %}
        {% set first_article_title = articles[0].Title %}
        <p>第一篇文章的标题是:{{ first_article_title }}</p>
    {% endif %}
{% endarchiveList %}

You can also combine with filters:

{% set raw_text = "Hello world! This is a test." %}
{% set truncated_text = raw_text|truncatechars:15 %}
<p>{{ truncated_text }}</p>