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 supported syntax structure is like mastering a 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 that of the Django template engine, which makes it easy for developers using Go language or users familiar with other template languages to master.It helps us easily achieve dynamic content display through a series of intuitive labels and filters.
Reference and display of dynamic data
The most basic and commonly used syntax is to use double curly braces to reference dynamic data. When we need to display variable values obtained from a database or other places in a template, we just need to use{{ๅ้ๅ}}This format. For example, to display the title of a document, we can write{{archive.Title}}; To display the name of a website, it 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 makes the static HTML skeleton instantly full of vitality, able to update automatically according to actual data.
Conditional 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 certain conditions.
The basic usage is{% if ๆกไปถ %} ... {% endif %}. If you need more complex logic, you can introduce{% elif ๅ
ถไปๆกไปถ %}(short for else if) to handle multiple exclusive conditions, as well as{% else %}As a fallback option when all conditions are not met. For example, we can determine whether the user is logged in to display different navigation menus, or decide whether to display image placeholders based on whether the article has a thumbnail.This structure allows the template to respond intelligently to data at runtime like program code.
loop traversal and list display
Website content is often presented in list form, such as article lists, product lists, category navigation, etc. The AnQiCMS template engine provides{% for ... in ... %}The tag is used to efficiently iterate over array or slice types of data. Inside the loop body, we can access the properties of the current iteration item and display them.
It is worth mentioning,forThe loop supports some very practical auxiliary functions. For example,{% empty %}Tags can display a preset content when the list is empty, to avoid blank pages or errors. In addition,forloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterObtains reverse index, these can all be used to add unique styles or behaviors to list items. If you need to traverse the list in a specific order (such as in reverse),reversedKeywords can be used directly inforused in labels, whilesortedIf supported, labels can help you sort by specific rules. These features greatly enhance the flexibility of list content display.
Data processing and formatting filter
The original data may not always meet our display requirements, such as formatting timestamps into readable dates, truncating long text, or safely outputting HTML content.Filters are born for this. They go through{{ๅ้|่ฟๆปคๅจๅ็งฐ:ๅๆฐ}}In the form, process the variable and output it afterwards.
Some very practical filters include:
stampToDate: This is a special filter of AnQiCMS, used to format timestamps into various date and time strings, such as{{item.CreatedTime|stampToDate:"2006-01-02"}}.safe: When the variable content contains HTML code and we want the browser to parse it as HTML rather than display it as plain text, we need to use|safeThis is crucial 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/truncatewordsUsed to truncate long strings or HTML content and automatically add ellipsis, commonly used to generate article summaries.add: Can perform simple arithmetic addition or string concatenation, for example{{price|add:discount}}.default/default_if_noneWhen a variable has no value (empty string, zero, nil, etc.), provide a default display value to avoid blank pages.lengthGet the length of a string, array, or map.escapejsUsed to safely embed strings into JavaScript code to avoid syntax errors or injection issues.
These filters constitute the powerful data processing capability in 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, the AnQiCMS template engine provides various structured and reusable mechanisms:
{% include "ๆไปถ่ทฏๅพ" %}: Used to insert the content of one template 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, footers, etc.) and use it in{% block ๅๅ %}Define a rewriteable area. Other templates simply inherit this base template, then rewrite the blocks that need to be customized, greatly reducing redundant code.{% macro ๅฎๅฝๆฐๅ(ๅๆฐ) %} ... {% endmacro %}: Allow us to define reusable code snippets, which 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 the template.withusually associates withincludeCombined, they are used to pass specific parameters to the included template;setis used to temporarily define variables within the current module block.
Data tags with specific functions and auxiliary tags
In addition to the general logical control and structural tags, AnQiCMS also integrates a large number of data tags for specific functions, greatly simplifying the complexity of data acquisition:
{% system ๅ้ๅ %}: Get the global settings of the website, such as the website name, Logo, filing number, etc.{% contact ๅ้ๅ %}: Conveniently get the contact information configured in the background.{% archiveList ๅ้ๅ %}: Get the list of articles or products, supporting multiple conditions for filtering by category, model, recommended attributes, sorting method, etc., and even supports pagination.{% categoryList ๅ้ๅ %}: Get category list, supporting multi-level nested categories.{% pageList ๅ้ๅ %}: Get single page list.{% pagination ๅ้ๅ %}: Coordinate.archiveListEqual pagination tags, conveniently generating pagination navigation links and status.
These tags encapsulate complex database query logic, allowing us to retrieve 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 white space in the template output, avoiding unnecessary blank lines or spaces to make the generated HTML cleaner.{% lorem %}Labels can be used to quickly generate placeholder random text during the template development stage, which is convenient for layout debugging.
AnQiCMS's template engine provides comprehensive syntax support from basic data display to complex logic control, and to the structured reuse of template structures.Mastering these grammatical constructs enables us to effortlessly manipulate the dynamic display of website content, providing visitors with a rich and interactive browsing experience.
Frequently Asked Questions (FAQ)
1. Why is the variable I am referencing 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 check that the variable names match the documentation or the backend data structure exactly. For example,
archive.titleandarchive.Titlethey are different. - Data was not 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 in
archiveListorcategoryListthe 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 a backup display. - Scope issues:especially in
includeormacroWhen using variables, if not usedwithpassing variables oronlyLimiting the scope may cause variables to become unavailable.
2. Can I directly execute complex programming logic or database queries in the AnQiCMS template?It is not recommended to directly execute complex programming logic or database queries in templates.The design concept of the AnQiCMS template engine is 'Logic and Presentation Separation', which mainly focuses on content display rather than business logic processing.The 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.The template ofif/forAnd filters are used for basic control flow and data formatting. The benefits of doing so are to improve code maintainability, testability, and ensure template security.If the data required in the template is not met, it should first consider adjusting the data provision method of the backend, or using built-in data tags (such asarchiveListto retrieve.
3. How to ensure the safety of template output and prevent XSS attacks?AnQiCMS template engine defaults to all passing through{{ๅ้}}The content output is HTML entity escaped, which can effectively prevent most