How to define temporary variables with the `with` tag in a template to better control content display logic?

Calendar 👁️ 65

When developing website templates on AnQiCMS, we often need to handle various data and decide the display method of the content according to this data.With the complexity of website functions, the logic in templates sometimes becomes difficult to understand and maintain.At this point, it is particularly important to master some advanced template tag usage, andwithTags are one of the practical tools that can significantly enhance the readability and control of templates.

withTags: a powerful tool for defining temporary variables in templates.

withTags allow us to define temporary variables within specific areas of a template. Its core function is to provide a local scope variable for a block of template code, and these variables are only valid within the{% with %}and{% endwith %}Labels between are valid. This locality greatly helps us manage the data flow in templates, avoiding conflicts in variable names and making the code structure clearer.

Imagine if the result of some complex data or expression needs to be used multiple times in a small segment of the template, or needs to pass specific contextual data to the public components introduced, directly repeating this complex logic will make the template long and difficult to read.withThe appearance of labels is to solve such problems. It provides a graceful way to declare temporary variables, making the subsequent logic more concise.

Why to usewithLabel? Enhance template development efficiency and maintainability

  1. Improve code readability and cleanliness:When a complex variable name or expression appears multiple times in a piece of logic, assigning it to a concise temporary variable makes the code intent clearer and easier to maintain. For example, if you need to use a data obtained through multiple layers frequently, such asarchive.Category.TitleDefine it temporarily ascurrentCategoryTitleIt makes the code easy to understand, reducing misunderstandings.
  2. Optimize the data processing process:Some data may need to be calculated or formatted in a series of steps to get the final result. If this result is used multiple times within a local scope, throughwithLabel it and store it as a temporary variable to avoid repeated calculations, thereby improving template rendering efficiency, especially when dealing with large amounts of data or complex calculation logic.
  3. Enhance template modularization ability: withwith the tag andincludeThe combination of labels is one of the most common application scenarios.When introducing a common template fragment (such as header navigation, sidebar widgets) often need to pass some specific data to this fragment.withLabels allow us to use:{% include "partial/header.html" with title="页面标题" keywords="SEO关键词" %}The form, provides the required environment variables to the template being introduced, thereby enabling data transmission between template components, making the components more generic and reusable.
  4. Refined content display logic:By adding inwithDefine boolean values, counters, or other status variables in tags, and we can control more flexiblyifJudgment orforLoop logic, for example, you can temporarily set aisFeaturedVariables to control the highlight display of a specific content, or to calculate and store an intermediate result in a loop to affect the display of subsequent elements.

withBasic usage example of the tag.

withThe use of labels is very intuitive, it always ends with{% with %}and ends with{% endwith %}which clearly defines the scope of the variable.

Define a single or multiple temporary variables:You canwithDefine variables directly within the label, like this:

{% with pageTitle="我的网站首页" %}
  <h1>欢迎访问 {{ pageTitle }}</h1>
{% endwith %}

If you need to define multiple variables, just separate them inwiththe tag with spaces and usekey=valuethe format as follows:

{% with pageTitle="我的网站首页" siteSlogan="用内容连接世界" %}
  <h1>{{ pageTitle }} - {{ siteSlogan }}</h1>
{% endwith %}

Please note, these variablespageTitleandsiteSloganonly{% with %}and{% endwith %}Valid between. Once they leave this block, they are no longer available.

CombineincludeTags pass data:As mentioned earlier,withTags play a huge role when introducing public templates. Suppose yourpartial/header.htmlneed atitlevariables andkeywordsVariables to build pages<head>Part:

{# partial/header.html 中的内容 #}
<head>
  <title>{{ title }}</title>
  <meta name="keywords" content="{{ keywords }}">
</head>

Introduce and pass data in the main template, just write the variable name and the corresponding value inwiththe parameters:

{% include "partial/header.html" with title="安企CMS官网" keywords="安企CMS,内容管理系统,GoLang" %}

Thus,partial/header.htmland it will use the one you passtitleandkeywordsThe value is rendered without affecting the同名 variable in the external template.

Actual application cases

Assuming you are developing an article detail page, you need to display the category name and publication year at the top of the page.This information may come from a complex object path or may require additional formatting.You can use it like thiswithLabel to simplify logic: “`twig {% archiveDetail currentArchive %} {# Assuming this tag has assigned the current article data to the archive variable #} {% with categoryName=currentArchive.Category.Title publishYear=stampToDate(currentArchive.CreatedTime, “2006”) %}

Article category: {{ categoryName }} | Publish

Related articles

How to use the `stampToDate` tag to format timestamps into a friendly date format to display content publication time?

During the operation of the website, the publication time of the content is an important part of conveying information to visitors.A clear and readable date format not only enhances user experience but also makes the website look more professional and timely.In AnQiCMS, the content publish time is usually stored in the form of a series of numbers (i.e., a timestamp).How can we convert these numbers into the familiar 'year-month-day' or 'month/day time:minute' formats that we are accustomed to?AnQiCMS provides us with a very convenient template tag: `stampToDate`.

2025-11-08

How to use `if` and `for` tags to implement conditional display and loop display of content in AnQiCMS templates?

In the AnQi CMS template world, flexibly controlling the display of content is the key to creating an engaging website.Whether it is to display different information based on specific conditions or to efficiently display a large amount of data, the `if` and `for` tags are indispensable tools for us.AnQiCMS's template engine adopts the syntax of Django, making these operations intuitive and powerful.### Understanding the `if` tag: Implementing conditional display of content The core function of the `if` tag is to decide whether to display a part of the content based on the conditions you set

2025-11-08

How `tdk` tags can dynamically generate and optimize SEO-related Title, Keywords, and Description for each page?

In modern website operation, the importance of Search Engine Optimization (SEO) is self-evident, and the page title (Title), keywords (Keywords), and description (Description), which we commonly refer to as TDK, are the "business card" of the website content on the Search Engine Results Page (SERP).They not only directly affect the click-through rate of the page, but are also key factors for search engines to understand the content of the page and rank it.AnQiCMS (AnQiCMS) fully understands the significance of TDK for SEO, and therefore in the system design

2025-11-08

How to dynamically fetch and display the global settings and contact information of the website using the `system` and `contact` tags?

In AnQi CMS, the global settings and contact information are the basic information that constitutes the important facade of the website.This information must be displayed accurately to visitors, and more importantly, it should be able to be updated and managed flexibly and conveniently without frequent modifications to the template code.AnQi CMS provides these two powerful tags, `system` and `contact`, allowing website operators to easily achieve dynamic acquisition and display of this information.

2025-11-08

How to correctly insert mathematical formulas and flowcharts in a Markdown editor and ensure they display normally on the web?

In content creation, especially in fields involving technology, science, or complex concepts, we often need to insert mathematical formulas or draw flowcharts to assist in explanation.The Markdown editor of AnQiCMS (AnQiCMS) has provided us with great convenience, allowing these complex elements to be input in a concise text form and presented elegantly on the web.How should we operate specifically to ensure that the content is displayed correctly?Firstly, make sure that your safety CMS system has enabled the Markdown editor.

2025-11-08

How does the search engine link push feature help new documents be indexed and displayed in search results quickly?

On the day of content release, how can your meticulously crafted website content be quickly discovered and indexed by search engines, which is a focus for every content operator.A newly released article or product page, if it can appear quickly in the search results, it will undoubtedly seize the initiative and bring valuable early traffic.AnQiCMS (AnQiCMS) fully understands this need and has specially provided a search engine link push feature to help your new document reach the search engine as quickly as possible, thereby speeding up indexing and display.Why is it important to be indexed quickly?

2025-11-08

How to configure custom rewrite rules to create more SEO-friendly content URLs?

The importance of URL structure in website operation is self-evident.A clear, concise, and keyword-rich URL not only improves user experience but also makes it easier for users to remember and share content, and can significantly optimize the crawling and ranking effects of search engines.Aqicms is well aware of this, therefore it provides a flexible and powerful pseudo-static rule configuration function to help users create more SEO-friendly content URL displays.What is the pseudo-static URL and its importance?So-called pseudo-static is not a real static page, but refers to URL rewriting technology through the server

2025-11-08

How to handle images (download remote, Webp, compress large images) to optimize page display speed in content settings?

As website operators, we all know that website loading speed is important for user experience and search engine rankings.Especially on content-rich websites, images are often a key factor affecting page speed.AnQiCMS (AnQiCMS) provides us with several very practical image processing features in the content settings, allowing us to flexibly optimize images and significantly improve the display speed of the website. ### Localizing remote images, controlling image resources During the process of content creation, we sometimes refer to images from other websites. At this time

2025-11-08