How to properly use variables and control tags in AnQiCMS templates to ensure correct display of content?

In AnQiCMS, the template is the core of website content display.Whether it is to build a corporate website or operate a content-rich blog, the correct display of content is inseparable from the standardized use of variables and control tags in the template.Mastering these basic knowledge can not only help us flexibly customize the website interface, but also effectively avoid potential display errors, ensuring the stable and efficient operation of the website.

The template syntax design of Anqi CMS draws inspiration from the Django template engine, with its core being the distinction between variable output and logical control. Variables are usually represented with double curly braces{{变量}}Perform definition and output, while logical operations such as conditional judgment and loop control are implemented using single curly braces and the percent sign{% 标签 %}Understanding this basic rule is the first step in our standardized use of templates.

The standardized use of variables: Accurately obtain and display data

In AnQiCMS templates, variables carry dynamic data of the website, such as article titles, category names, and system settings. To ensure that the content is displayed correctly, we need to pay attention to the following aspects:

  1. Understanding the origin and context of variables:

    • Direct data field:When iterating over list data in a loop, such as{% for item in archives %},itemThe variable will contain multiple data fields of the current loop item, for example{{item.Title}}Used to display the article title,{{item.Link}}Used to display article links. Here, the variable nameitemfollowed by a period., then the field name (for exampleTitle/Link), this method is concise and efficient.
    • specific tagsnameParameters:Some tags, such assystem(System settings),contact(Contact Information),archiveDetail(Document Details),categoryDetail(Category details) allow us toname="字段名称"retrieve the value of a specific field using parameters. For example,{% system with name="SiteName" %}This will directly output the website name. If we want to assign this value to a temporary variable for subsequent use, we can write it like this:{% system siteNameVar with name="SiteName" %}{{siteNameVar}}This method provides great flexibility, especially when it comes to retrieving specific information.
    • Camel case naming convention and strict distinction between uppercase and lowercase:The variable names in AnQiCMS templates follow camelCase naming conventions, for exampleitem.CreatedTimeInstead ofitem.created_time. Moreover, the template engine strictly distinguishes between variable names and tag names in terms of case sensitivity.{{item.Title}}and{{item.title}}Will be treated as different variables, if the case does not match, it may likely cause the content to not display or result in an error.
  2. Data structure and calling method:

    • Object properties:Most details page data (such asarchiveDetailreturnedarchiveobjects) and list items (such asarchiveListIn the loopitem) are objects, and we can access their internal data by对象名.属性名.)
    • Array/slice:List label (such asarchiveList/categoryList) usually returns a data set, and needs to be used with{% for ... %}loop tags to process each item. Some fields may also be image arrays, such asImagesField, it also needs to be displayed through a loop.

The Art of Controlling Tags: Harnessing Template Logic and Structure

The control label is a key feature in AnQiCMS template that implements logical judgment, looping, modularization, and code reuse.Their correct use directly relates to the accuracy of page layout and data display.

  1. Conditional judgment:if/elif/else/endifWhen we need to display or hide content based on specific conditions,ifLabels are indispensable. They allow us to check if a variable exists, if it is true, if it is equal to some value, etc. For example, to display a picture only if it exists:{% if item.Thumb %}<img src="{{item.Thumb}}" alt="{{item.Title}}"/>{% endif %}This helps to avoid displaying empty placeholder images or page structure confusion due to missing data.

  2. Loop traversal:for/empty/endforFor displaying list data,forLoops are central. They iterate over each element in a collection and allow us to access the current element within the loop body. A common auxiliary tag isemptywhen the collection in the loop is empty,emptyLabel content will be displayed. This is very useful for handling situations such as "No content", enhancing user experience. In addition,forloop.CounterThe built-in variables can help us control the index or specific style in the loop.

  3. Variable assignment and scope:with/set withLabels are used to define temporary variables within specific blocks of a template. These variables are only valid between{% with %}and{% endwith %}. This helps to avoid name conflicts and maintain code clarity. For example:{% with tempTitle = item.Title|upper %}{{tempTitle}}{% endwith %}.setThe label can be declared at any position within the current template, and its scope is usually larger, until the template rendering is completed.

  4. Template reuse and inheritance:include/extends/macro

    • include:Used to introduce content from other template files, which is the most direct way to implement modular layout. For example, the header and footer can be extracted into independent files and then included in each page.{% include "partial/header.html" %}.includeIt can also be done throughwithPass parameters, even usingif_existsto avoid errors caused by non-existing templates.
    • extends:To implement template inheritance, define a basic skeleton (likebase.html), other pages can pass through{% extends 'base.html' %}Inherit and overwrite the one definedblockBlock. This is crucial for maintaining the consistency of the overall website style, improving development efficiency, and reducing maintenance costs.
    • macro:Similar to functions in programming languages, macros can define reusable code blocks within templates and pass data through parameters. Macros can be defined in separate files and accessed byimportIntroducing. It provides a more advanced code reuse mechanism, especially suitable for generating repetitive HTML structures with slightly different parameters.

Smart use of filters: fine-tune data processing

Filters (Filters) is a powerful tool for converting and formatting variable values in AnQiCMS templates, used|Connect variables and filters. They ensure that data is displayed in the format we expect, further enhancing the accuracy and aesthetics of the content.

  1. Safe output:|safeWhen the variable contains HTML code (such as the content generated by a rich text editor), if it is output directly, the template engine may escape it to plain text for security reasons. At this time, we need to use|safeThe filter tells the engine that this content is safe and can be rendered directly as HTML. For example:{{archive.Content|safe}}Remember not to overuse.|safeIt may introduce XSS risk, use it only where HTML rendering is indeed necessary.

  2. Time formatting:stampToDateThe timestamp obtained from the database is usually not easy to read.stampToDateLabels can convert timestamps into human-friendly date and time formats.