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 AnQiCMS's template engine (similar to Django or Blade syntax) is intuitive and easy to use, mastering some debugging techniques can make a big difference.
We usually delve into the variables and data structures within the template in the following ways.
1. Utilizedumpfilters to quickly view variable details
Imagine you encounter a variable in a template and are unsure what data it contains, whether it's 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.|dumpIt is. For example:
{# 调试一个名为 `archive` 的变量 #}
<pre>{{ archive|dump }}</pre>
{# 调试一个列表 `archives` 中的单个 `item` #}
{% for item in archives %}
<pre>{{ item|dump }}</pre>
{% endfor %}
When you access the corresponding page, a text block containing the detailed information of the variable (including its Go language struct name, field types, and current value) will be output in the browser.This is like taking an X-ray of a variable, allowing you to clearly see its 'skeleton' and 'internal organs', thereby determining whether it is the expected data type and content.&config.Archive{Id:1, Title:"我的文章", ...}This output can help you understand the name and type 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 ofstringformatDeeply analyze the structure type of the filter
Exceptdump, another practical filter to understand the intrinsic structure of variables isstringformatIt allows you to print variables in the format of the Go language. Particularly, using%#vCan print out 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 instead of its full 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 more thandumpMore concise, especially when dealing with nested structures, it can provide a clearer hierarchical view, allowing you to quickly locate issues in the data structure.
3. Use conditional judgment and loop structures for local validation
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 some condition, or iterate over its contents. AnQiCMS template engine'sifandforThe tag can be used here.
Conditional judgment (
if):You can use{% if variable %}Check if a variable exists and is not empty (for strings, numbers, lists, etc.). To determine if a field is equal to a specific value, you can use{% if archive.Id == 10 %}this syntax.{# 检查 `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,forLoop is the **way to view the content of each element. You can combine it inside the loop todumporstringformatcheck eachitemat the same time,forLoops also provideforloop.Counter(current loop count) andforloop.Revcounter(remaining loop count) and other auxiliary variables to help you understand the progress of iteration.emptyLabels can display prompt information 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. UsesetorwithLabel to define a temporary variable
When handling complex data structures, or when you want to step-by-step debug an expression,setandwithTags will be your helpful assistant.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 and define multiple temporary variables within the block, which are only valid in thatwithblock.{% 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 complex objects for debugging.
5. Pay attention to the case sensitivity of variable names and data types.
In the template development of AnQiCMS, be sure to remember that variable names arecase-sensitiveThe. 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 names match exactly.
Moreover, when using filters (such asstampToDateTimestamp is required,dateRequiredtime.TimeWhen a 【type】 is specified, ensure that the data type passed in is correct. If the types do not match, the filter may not work properly, leading to abnormal output or blank results.
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. This is usually due to the security mechanism of the template engine, which prevents XSS attacks. If your variable indeed contains code that needs to be parsed as HTML (such as article details content)Content)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 (even though AnQiCMS automatically escapes HTML by default).
By flexibly applying the above debugging techniques, you will be able to more efficiently troubleshoot problems encountered during AnQiCMS template development, ensuring the correct output and display of page content.
Common Questions (FAQ)
Why is my template variable output blank?There are usually several reasons for outputting blank:
- The variable does not exist or is empty:Check if the variable is available in the current context and whether there is actual data. It can be used
{% if myVariable %}to determine. - Variable name case error:AnQiCMS template variable names are strictly case-sensitive. Please make sure your variable names are exactly consistent with those defined in the backend or label documents (usually camelCase).
- Data type mismatch:If you apply a filter (such as date formatting, truncation, etc.) to 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 ascategoryIdnot exist,moduleIderror), it may cause the data retrieval to fail.
How do 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 dynamically changing. However, you can obtain most of the information by debugging key global tags:
- System Settings:Use
{% system with name="SiteName" %}Waiting to fetch. - Details of the current page or document:On the corresponding page,
archive(Document),category(Category)、pageVariables such as (Single Page)etc. are usually automatically injected, and you can use them directly.|dump. - TDK Information:Use
{% tdk with name="Title" %}etc. tags. - Navigation List:Use
{% navList navs %}Retrieve navigation data. By analyzing the outputs of these core variables and tags,|dumporstringformat:"%#v"you can gradually understand the data structure available on the current page.
Why are the HTML tags in my article content not rendered and instead displayed as raw text?<p>/<a>What is the meaning of this text?This is because the AnQiCMS template engine, for security reasons, defaults to escaping all output content to prevent malicious script injection (XSS attacks). If your article contentarchive.ContentThe content indeed includes 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, using|safemeans you trust the security of this content, be sure to ensure the reliability of the content source.