When developing templates in AnQi CMS, understanding and debugging the output of variables and the structure type of data is the key to improving efficiency.Although the AnQiCMS template engine (similar to Django or Blade syntax) is intuitive and easy to use, mastering some debugging techniques can make a big difference in problem-solving.
We usually delve into the variables and data structures in templates in the following ways.
1. UsedumpFilter quickly view variable details.
Imagine that you encounter a variable in a template and are unsure what kind of data it contains, whether it is a string, number, list, or a more complex structure? At this point, AnQiCMS provides a very direct and powerful tool -dumpfilter.
You just need to add it after the variable you want to debug|dump.
{# 调试一个名为 `archive` 的变量 #}
<pre>{{ archive|dump }}</pre>
{# 调试一个列表 `archives` 中的单个 `item` #}
{% for item in archives %}
<pre>{{ item|dump }}</pre>
{% endfor %}
When you visit the corresponding page, the browser will output a text block containing detailed information about the variable (including its Go language struct name, field type, and current value).This is like taking an X-ray of a variable, allowing you to clearly see its 'skeleton' and 'viscera,' thereby determining whether it is the expected data type and content.For example, you might see something similar&config.Archive{Id:1, Title:"我的文章", ...}This output will help you understand the names and types of each field. To better display the output, it is recommended to wrap it in<pre>Labels within, to maintain the format.
2. With the help ofstringformatIn-depth analysis of the structure type through the filter
exceptdumpAnother practical filter to understand the intrinsic structure of variables isstringformatIt allows you to print variables in the formatting rules of the Go language. Specifically, using%#vIt can print the source code representation of a variable in Go language, which is very helpful for understanding the fields and default values inside complex structs.
If you only want to quickly know the Go language type of a variable, not its complete content, you can use%T.
{# 查看 `archive` 变量的Go语言源代码表示 #}
<pre>{{ archive|stringformat:"%#v" }}</pre>
{# 仅仅查看 `archive` 变量的Go语言类型 #}
<p>变量 `archive` 的类型是:{{ archive|stringformat:"%T" }}</p>
The output of this method is usually moredumpMore concise, especially when dealing with nested structures, it can provide a clearer hierarchical view, allowing you to quickly locate problems in the data structure.
3. Use conditional judgment and loop structures for local verification
Many times, we may not need to know all the details of a variable, but just want to simply judge whether it exists, whether it meets certain conditions, or traverse its content. The AnQiCMS template engine'sifandforThe label can be put to good use here.
Conditional judgment (
if):You can use{% if variable %}Check if a variable exists and is not empty (for strings, numbers, lists, etc.). If you want to check if a field is equal to a specific value, you can use the syntax{% if archive.Id == 10 %}such as this.{# 检查 `archive` 变量是否存在 #} {% if archive %} <p>archive 变量存在</p> {% else %} <p>archive 变量不存在</p> {% endif %} {# 检查 `archive.Title` 是否等于特定值 #} {% if archive.Title == "调试文章" %} <p>这是调试文章!</p> {% endif %}Loop through (
for):For variables of list or array type,forLoops are the way to view each element's content. You can combine them inside the loop.dumporstringformatto check each one individuallyitem. At the same time,forThe loop also providesforloop.Counter(current loop count) andforloop.Revcounter(remaining loop count) and other auxiliary variables, helping you understand the progress of iteration.emptyThe label can display a prompt message when the list is empty.{# 遍历 `categories` 列表并显示每个分类的标题和链接 #} {% for category in categories %} <p>第 {{ forloop.Counter }} 个分类:<a href="{{ category.Link }}">{{ category.Title }}</a></p> {% empty %} <p>没有找到任何分类</p> {% endfor %}
4. UsesetorwithTags define temporary variables.
When dealing with complex data structures, or when you want to step-by-step debug an expression,setandwithTags can be a great helper. They allow you to define temporary variables in templates, so you can break down a complex data path into smaller, more manageable pieces, and then debug each piece step by step.
setTags:Used to define a variable within the current template scope.{# 定义一个临时变量 `myTitle` #} {% set myTitle = archive.Title|upper %} <p>处理后的标题:{{ myTitle }}</p> {# 此时你可以单独调试 `myTitle` #} <pre>{{ myTitle|dump }}</pre>withTags:Used to enclose a block of code, where multiple temporary variables are defined, and these variables are only valid withinwiththe block.{% with tempArchive = archive, tempCategory = archive.Category %} <p>当前文章ID:{{ tempArchive.Id }}</p> <p>所属分类名称:{{ tempCategory.Title }}</p> {% endwith %}This is very convenient when it is necessary to extract multiple properties from a complex object for debugging.
5. Pay attention to the case sensitivity and data type of variable names.
In AnQiCMS template development, always remember that the variable name isStrictly distinguish between uppercase and lowercaseThe. AnQiCMS template variable names usually follow the CamelCase naming convention, which meansarchive.titleandarchive.TitleIt is completely different. If your output is blank, first check if the variable name matches exactly.
In addition, when you use filters (such as)stampToDateTimestamp is required,daterequiredtime.TimeEnsure that the data type is correct when passing the data to the filter. If the type does not match, the filter may not work properly, leading to abnormal output or blank.
6. HTML content escaping issue
You may encounter a situation where HTML content is output as plain text instead of being parsed by the browser, which is usually due to the security mechanism of the template engine to prevent XSS attacks. If your variable indeed contains code that needs to be parsed as HTML (such as article details contentContent),you need to use|safeThe filter explicitly tells the template engine that this content is safe and does not need to be escaped.
{# 假设 `archive.Content` 包含HTML代码 #}
<div>
{{ archive.Content|safe }}
</div>
On the contrary, if you need to display HTML tags as plain text, you can use|escapeFilter (although AnQiCMS defaults to automatically escaping HTML).
By flexibly applying the above debugging techniques, you will be able to more efficiently troubleshoot the problems encountered in AnQiCMS template development, ensuring the correct output and display of page content.
Frequently Asked Questions (FAQ)
1. Why is my template variable output blank?There are usually several reasons for blank output:
- The variable does not exist or is empty:Check if the variable is available in the current context and whether there is actual data. You can use
{% if myVariable %}to judge. - Variable name case error:The variable names in AnQiCMS templates are case-sensitive, please ensure that your variable names match the definitions in the backend or label documents (usually camel case).
- Data type mismatch:If you use a filter (such as date formatting, truncation, etc.) on a variable but the data type of the variable does not match the requirements of the filter, it may also result in an empty output.
- Label parameter error:If using built-in labels (such as
archiveList) to retrieve data, but the label parameter is set incorrectly (such ascategoryIddoes not exist,moduleIderror), it may cause data retrieval failure.
2. How can I view all available data in the template (including backend settings, current page information, etc.)?You cannot directly dump all global data within a tag because the template context is dynamic. However, you can obtain most information by debugging key global tags.
- System Settings:Use
{% system with name="SiteName" %}Wait to get. - Current page or document details:On the corresponding page,
archive(Document),category(Categories),page(Single page) and other variables are usually automatically injected, you can use them directly.|dump. - TDK Information:Use
{% tdk with name="Title" %}Tags - Navigation list:Use
{% navList navs %}Get navigation data. By outputting these core variables and tags,|dumporstringformat:"%#v"you can gradually understand the data structures available on the current page.
3. Why are the HTML tags in my article content not rendered but displayed as raw text instead?<p>/<a>And the text?This is because the AnQiCMS template engine, for security reasons, defaults to escaping all output content to prevent malicious script injection (XSS attack). If your article contentarchive.ContentThis indeed contains HTML code that needs to be parsed by the browser, you need to use|safea filter to explicitly tell the template engine that this content is safe and does not need to be escaped. For example:{{ archive.Content|safe }}Please note that using|safeIt means you trust the security of this content, be sure to ensure the reliability of the source.