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

Variable declaration method in Anqi CMS template

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

Use{% with %}Temporarily assign the tag

{% with %}Tags are mainly used for assigning temporary variables in specific module blocks, their lifecycle is limited to the{% with %}and{% endwith %}code block between. This makeswithTags are very suitable for passing parameters to local template fragments (partial) or temporarily simplifying variable names in 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 introduce a common header (header) fragment in a template and want to pass a specific page title and keywords to this fragment,withTags are especially practical. Suppose we have apartial/header.htmltemplate file that needstitleandkeywordstwo variables to generate the page<title>and<meta name="keywords">tags. We can use them 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 if{% with %}and{% endwith %}Valid inside. Passedincludelabel'swithParameters, we pass these variables topartial/header.html.onlyThe keyword ensuresheader.htmlReceived only explicitly passed variables, and will not inherit all variables in the current template, thus avoiding potential variable conflicts.

Use{% set %}Declare local variables with the tag

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

setThe syntax of tags 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, on a document list page, we may need to retrieve the title of the first article in the current document list and use it in a specific area of the page. UsingsetTags 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 %}Tags rendered out:if articlesDeclared within a block and used in the subsequent content of the block.

Using variables and output

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

For example, you can apply a string variable totruncatecharsA filter to truncate its length, or perform arithmetic operations such as addition, subtraction, multiplication, and division 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>

Application scenarios in practice

Custom variables have a wide range of applications in AnQi CMS template development, including but not limited to:

  • Pass data to a reusable component: Pass specific data or configuration items from the parent template through{% with %}pass to{% include %}to the child template, achieving high reusability of the component.
  • Simplify complex expressionsStore complex data paths or calculation results in a short variable to improve template readability and maintainability.
  • Temporary data storageIn a loop or conditional judgment, temporarily store an intermediate result for subsequent logic.
  • Dynamic content adjustment:According to the user's permissions or configuration, dynamically assign values and adjust display content, such as displaying different greetings or buttons.

Through proficiency{% with %}and{% set %}These variable declaration methods allow you to build secure CMS website templates more flexibly and efficiently, achieving complex and dynamic content display requirements.

Frequently Asked Questions (FAQ)

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

{% with %}Variables declared with tags are only in their{% with %}and{% endwith %}valid within the code block, it is mainly used to pass temporary data to local template fragments or to simplify variable names in specific code blocks.{% set %}The variable declared by the tag usually throughout the current template file (or the nearest one that declared it)blockBlocks can be accessed anywhere, its scope is wider, suitable for storing values or calculation results that need to be used in multiple places in the template.

2. Can the declared variable be used directly in other template files?

Accessed 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, by{% include %}Introducing the child template), you need to explicitly pass through{% include "path/to/template.html" with variable_name=your_variable %}Pass it in this way. For{% set %}Declared variables, if you declare them in the parent template and then use them in the child template{% include %}Reference this sub-template, the sub-template can inherit the environment of the parent template unless youincludeused in theonlykeywords.

3. How to{% set %}use the result of other tags for assignment?

You can{% set %}Combine the output or variable of other tags with filters to assign values. For example, toarchiveListAssign the title of the first article obtained by the tag 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 filters:

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