In AnQiCMS, the template engine plays a core role, responsible for displaying the dynamic data obtained from the backend in the layout and style we preset to visitors.Understanding the syntax structure it supports is like mastering the language to 'talk' with the website content, allowing us to flexibly control the display of information, thereby creating highly personalized and dynamic website experiences.

AnQiCMS's template engine adopts a syntax style similar to Django's template engine, which makes it relatively easy for both Go language developers and users familiar with other template languages to master.It helps us easily achieve dynamic content display through a series of intuitive tags and filters.

Reference and display of dynamic data

The most basic and most commonly used syntax is to use double curly braces to refer to dynamic data. When we need to display variable values obtained from a database or other places in the template, we simply use{{变量名}}such format. For example, to display the title of a document, we can write{{archive.Title}}; to display the name of a website is{{system.SiteName}}.These variables usually follow camel case naming conventions, with the first letter capitalized, making the code more readable.This direct reference to variables gives the static HTML skeleton instant vitality, allowing it to automatically update based on actual data.

condition judgment and logical control

It is not enough to just display data, often we need to display different content blocks based on different conditions. At this time,{% if ... %}Labels are particularly important. They allow us to make logical judgments based on the value of variables. For example, to determine if a list is empty, or if a specific field meets a certain condition.

The basic usage is{% if 条件 %} ... {% endif %}. If you need more complex logic, you can introduce{% elif 其他条件 %}(short for else if) to handle multiple mutually exclusive conditions, as well as{% else %}As an alternative solution when all conditions are not met.For example, we can determine if a user is logged in to display different navigation menus, or decide whether to display an image placeholder based on whether the article has a thumbnail.This structure allows the template to respond intelligently to data at runtime, just like program code.

looping through and displaying lists

Content on websites is often presented in the form of lists, such as article lists, product lists, category navigation, etc. The AnQiCMS template engine provides{% for ... in ... %}Label to efficiently iterate over array or slice type data. Within the loop body, we can access the properties of the current iteration item and display them.

It is worth mentioning that,forLooping also supports some very practical auxiliary functions. For example,{% empty %}Tags can display a preset content when the list is empty, avoiding blank pages or errors. Moreover,forloop.CounterCan retrieve the current loop index (starting from 1),forloop.RevcounterThen obtain the reverse index, all of which can be used to add unique styles or behaviors to list items. If you need to iterate through the list in a specific order (such as in reverse),reversedkeywords can be used directly inforUsed in tags, whereassortedIf supported by the tag, it can help you sort by specific rules. These features greatly enhance the flexibility of displaying list content.

Data processing and formatting filter

The original data may not always meet our display requirements, for example, timestamps need to be formatted into readable dates, long texts need to be truncated, or HTML content needs to be safely output.The Filters are born for this.{{变量|过滤器名称:参数}}The variable is processed and then output in the form of.

Some very practical filters include:

  • stampToDateThis is a unique filter of AnQiCMS, used to format timestamps into various date-time strings, such as{{item.CreatedTime|stampToDate:"2006-01-02"}}.
  • safeWhen the variable content includes HTML code and we want the browser to parse it as HTML instead of displaying it as plain text, we need to use|safeThis is especially critical when displaying the output content of a rich text editor, but it is necessary to ensure the safety of the content source to prevent XSS attacks.
  • truncatechars/truncatewords: Used to truncate overly long strings or HTML content and automatically add ellipses, often used to generate article summaries.
  • addCan perform simple arithmetic addition or string concatenation, for example{{price|add:discount}}.
  • default/default_if_noneWhen the variable has no value (empty string, zero, nil, etc.), provide a default display value to avoid the page from showing blank.
  • lengthGet the length of a string, array, or map.
  • escapejsUsed to safely embed strings into JavaScript code, avoiding syntax errors or injection issues.

These filters constitute the powerful data processing capabilities of the template, allowing us to present data in the most elegant way.

Template structure and reuse mechanism

To improve the maintainability and development efficiency of the template, AnQiCMS template engine provides various structured and reusable mechanisms:

  • {% include "文件路径" %}: Used to insert the content of one template file into another. This is very suitable for reusing small pieces of content such as headers, footers, sidebars, etc.
  • {% extends "基础模板" %}Implement template inheritance. We can define a basic template that includes common website structures (such as HTML headers, navigation, and footers), and use it in{% block 块名 %}Define a reusable area. Other templates simply inherit this base template and then overwrite the blocks that need customization, greatly reducing repetitive code.
  • {% macro 宏函数名(参数) %} ... {% endmacro %}Allow us to define reusable code snippets; these macros can be called like functions and can be imported into other templates, providing high modularity.
  • {% with 变量名=值 %}and{% set 变量名=值 %}These two tags are used to define local variables in templates.with Usually goes withinclude Used together, to pass specific parameters to included templates;set Used to define temporary variables within the current template block.

Data tags with specific features and auxiliary tags

In addition to the general logic controls and structural tags, AnQiCMS also includes a large number of data tags for specific functions, greatly simplifying the complexity of data acquisition:

  • {% system 变量名 %}[en]: Get the global settings of the website, such as website name, Logo, record number, etc.
  • {% contact 变量名 %}[en]: Easily get the contact information configured in the background.
  • {% archiveList 变量名 %}Get a list of articles or products, supporting multiple conditions for filtering such as categories, models, recommended attributes, sorting methods, and even pagination.
  • {% categoryList 变量名 %}: Get category list, supporting multi-level nested categories.
  • {% pageList 变量名 %}: Get single page list.
  • {% pagination 变量名 %}: In coordination witharchiveList evenly divided pagination labels, conveniently generating pagination navigation links and status.

These tags encapsulate complex database query logic, allowing us to obtain the required data declaratively in the template without concerning ourselves with the underlying implementation details.

Finally, there are some detail control tags like{%-and-%}Used to precisely control the whitespace characters in the template output, avoiding unnecessary blank lines or spaces, making the generated HTML cleaner.{% lorem %}The label can generate placeholder random text quickly during the template development phase, which is convenient for layout debugging.

The AnQiCMS template engine provides comprehensive syntax support ranging from basic data display to complex logic control, and to the structured reuse of template structures.Mastering these grammars allows us to effortlessly navigate the dynamic display of website content, providing visitors with a rich and interactive browsing experience.


Common Questions (FAQ)

Why is the variable I refer to in the template not displaying content or showing as empty?This usually has several reasons:

  • Variable name spelling error:Template variables are case-sensitive, please carefully check that the variable names match the document or the data structure provided by the backend exactly. For example,archive.titleandarchive.Titleare different.
  • Data has not been passed to the template:Ensure that the backend logic has correctly retrieved the data and passed it to the current rendering template. If it is inarchiveListorcategoryListthe loop, make sure the loop itself has data.
  • The data is empty or does not exist:Sometimes a variable may indeed have no value (for example, an article may not have a thumbnail), in which case you can consider using|default:"默认值"a filter to provide an alternative display.
  • Scope issues:Especially inincludeormacroWhen using variables, if not usedwithpass variables oronlylimit the scope, it may cause the variable to be unavailable.

Can I directly execute complex programming logic or database queries in the AnQiCMS template?Do not recommend executing complex programming logic or database queries directly in the template.The design philosophy of AnQiCMS template engine is 'Separation of Logic and Presentation', which mainly focuses on content display rather than business logic processing.Complex business logic and data queries should be completed on the backend (controller/model), and then the processed, structured data should be passed to the template.if/forAnd filters are used for basic control flow and data formatting.The benefits of doing this include improving code maintainability, testability, and ensuring the security of the template.archiveListetc.) to obtain them.

How to ensure the safety of template output and prevent XSS attacks?AnQiCMS template engine defaults to processing all through{{变量}}Output content should be HTML entity encoded to effectively prevent most