In Anqi CMS, when managing website content, we often find that using temporary variables flexibly in templates can make the code more concise, efficient, easy to understand, and maintain.The Anqi CMS template system has borrowed the syntax of the Django template engine, providing a straightforward way to define and use these temporary variables.
Temporary variables make the template more concise and efficient
Why do we need to define temporary variables in the template?Imagine if you need to display a piece of data that has been processed complexly at different positions on a page, such as the first image extracted from a list or a calculated result.If there are no temporary variables, you may need to repeat the same logic or expression at each usage, which not only makes the template code long-winded but also reduces the rendering efficiency of the page.
By defining temporary variables, we can store these values and reuse them in multiple places in the template, greatly enhancing the readability and maintainability of the code.This is like giving a shorthand for a complex concept when writing an article, and then using the shorthand throughout, which can keep the writing smooth and help the reader understand quickly.
The Anqi CMS template mainly provides two ways to define temporary variables:{% set %}and{% with %}They have different focuses and are suitable for different scenarios.
Use{% set %}Define variables easily
{% set %}It is the most commonly used and most direct way to define a temporary variable in Anqi CMS template. Its syntax is very simple:{% set 变量名 = 值 %}Once defined, the variable can be used in{% set %}Used within the current template scope after the label until the template is parsed.
You can assign various types of values to it, such as strings, numbers, even other tags or filter results.
For example, on the article detail page, we may need to refer to the first image of the article multiple times as a cover, or we may need to format the publication time of the article. At this point,{% set %}it comes in handy:
{# 假设 archive.Images 是一个图片链接的数组 #}
{% set firstImage = archive.Images[0] %}
{% set formattedTime = stampToDate(archive.CreatedTime, "2006年01月02日") %}
<div class="article-header">
<img src="{{ firstImage }}" alt="{{ archive.Title }}">
<h1>{{ archive.Title }}</h1>
<p>发布时间:{{ formattedTime }}</p>
</div>
<div class="article-body">
{# ... 文章内容 ... #}
<p>文章封面图:<img src="{{ firstImage }}" alt=""></p>
<p>更新日期:{{ formattedTime }}</p>
</div>
In this example,firstImageandformattedTimeDefined as a temporary variable, avoiding repetition.archive.Images[0]andstampToDate(...)Such an expression makes the code clearer and easier to understand.
Utilize{% with %}Building a local scope
Compared to{% set %}the visibility of the variable throughout the template,{% with %}Tags provide a more 'enveloping' way of defining variables. Its syntax is{% with var1="value1" var2="value2" %} ... {% endwith %}. The variables defined here are only{% with %}and{% endwith %}valid within this range, once outside this range, these variables no longer exist.
{% with %}this local scope feature makes it particularly useful in the following scenarios:
Pass multiple variables to the template:When you use
{% include %}When a tag includes a small template snippet,{% with %}It can help you clearly pass a group of local variables to this snippet without polluting the parent template's namespace.For example, we have a
partial/header.htmlIt needs to display the website title and keywords:{# index.html #} {% with pageTitle="安企CMS官网 - 轻松建站" pageKeywords="安企CMS, Go语言CMS, 企业建站" %} {% include "partial/header.html" %} {% endwith %} {# partial/header.html #} <head> <title>{{ pageTitle }}</title> <meta name="keywords" content="{{ pageKeywords }}"> </head>Thus,
partial/header.htmlcan be used directlypageTitleandpageKeywordsand these variables will not affectindex.htmlthe naming of variables in other parts.Define a set of related variables within a code block:If you need to perform a series of complex calculations or data processing within a specific logical block, and generate multiple temporary values,
{% with %}Encapsulate these temporary values in this block to maintain code cleanliness.{% with totalSales = product.Price * product.Quantity, discountRate = 0.1 %} <p>总销售额:{{ totalSales }}</p> <p>优惠金额:{{ totalSales * discountRate }}</p> {% endwith %} {# 在这里,totalSales 和 discountRate 就不再可用了 #}
Practical application scenarios and insights
- Avoid repeated calls and calculations:When a piece of data (such as the query results of a tag) needs to be rendered multiple times in a template, it can be assigned to a temporary variable to avoid repeated query execution, which improves the page loading speed.
- Enhance readability and maintainability:Break down complex expressions into several smaller temporary variables, which can make the template logic clear.When you need to modify a value, you only need to modify the line where the temporary variable is defined, rather than modifying it in all the places where it is used.
- Optimize condition judgment:Sometimes, the condition may be a complex expression. We can first store the result of the expression in a temporary boolean variable, and then use this variable for the conditional judgment, in order to
{% if %}The statement is clearer.
Mastered{% set %}and{% with %}These two ways of defining temporary variables will allow you to be more agile in the template development of Anq CMS.Using them reasonably can not only make your template code cleaner, but also present the website content to users more efficiently.
Frequently Asked Questions (FAQ)
1.{% set %}and{% with %}What is the core difference when defining temporary variables?
The main difference lies in their scope.{% set %}Variables defined once are visible and usable throughout the remaining part of the current template. And{% with %}are only accessible within{% with %}and{% endwith %}The code block within the tags is effective. Usually,{% set %}It is suitable for general variables that need to be reused in multiple places in the template, whereas{% with %}it is more suitable to provide context variables for specific local code blocks (such as{% include %}introduced fragments) to avoid variable name conflicts.
2. Can I use a temporary variable in the loop (for)?
Of course. In{% for %}In loops, defining temporary variables is a common operation, their scope is limited to the current loop iteration. For example, you can calculate and store the attribute of the current element in each loop iteration, or based on the loop counter (forloop.Counter) Generate some special values.
`twig {% for item in archives %}
{% set articleLink = item.Link %}
{% set displayTitle