What methods does AnQiCMS provide for template developers to debug variable output and structure type?

Calendar 👁️ 66

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 asarchiveList) 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.

Related articles

How do user group management and VIP systems affect the access permissions and display of specific content?

How to allow different users to see different content on a website, even charging for some high-value content, is the key to enhancing the value of the website and achieving monetization.AnQiCMS provides powerful and flexible features in user group management and VIP system, helping us achieve refined content distribution and differentiated display. ### Understanding the Core Value of User Groups and VIP Systems In Anqi CMS, user group management is the foundation for building personalized content experiences.

2025-11-09

How to use the 'safe output' mechanism of AnQiCMS template to avoid HTML content from being escaped?

In website content management, we often need to display various text information on the page, including HTML content with specific formats or interactive effects.AnQiCMS (AnQiCMS) is a modern content management system that, by default, takes an important security measure when handling template rendering: automatically escaping HTML content.This mechanism is designed to prevent cross-site scripting (XSS) attacks and ensure website security.However, in certain specific scenarios, such as when we want to display formatted content edited by a rich text editor, or custom HTML code snippets

2025-11-09

How to ensure that the URL strings in the content are automatically converted into clickable hyperlinks?

In daily website content operations, we often need to include various links in articles or descriptions, whether they point to other pages within the site or external references.One of the key aspects of user experience is that these URL strings can be automatically turned into clickable hyperlinks, rather than a series of cold texts.AnQiCMS (AnQiCMS) fully understands this and provides a variety of flexible and efficient methods to help us ensure that URLs in the content can be intelligently converted into clickable hyperlinks.Next, we will discuss how to achieve this goal in AnQiCMS

2025-11-09

How to automatically convert multiline text content to HTML format with <p> or <br> tags for display?

In website content display, we often encounter such needs: multi-line text edited in the background can be automatically converted into a format with HTML paragraph tags `<p>` or line break tags `<br>` on the front-end page, rather than simply being compressed into a long string of text.AnQiCMS provides a flexible and powerful method to solve this problem, whether it is through built-in editor features or by using template filters for precise control, it can be easily realized.### One, use the content editor to achieve automatic conversion When you go through AnQiCMS

2025-11-09

How to define and assign variables in a template to temporarily control the display logic of content?

In AnQi CMS template development, flexibly defining and assigning variables is the key to dynamic display of website content and personalized layout.By cleverly using variables, we can temporarily adjust the presentation of content, making the template not only able to carry basic data display but also able to present a rich and varied display logic according to specific conditions.This article will deeply explore how to define and assign variables in AnQiCMS templates, as well as their actual application in controlling the display logic of content.### The Foundation of Template Variables

2025-11-09

How to use the 'Remove logical tag line occupation' feature to clean up extra blank lines rendered by the template?

When using AnQi CMS to manage a website, we all hope that the page presented to the visitor is both beautiful and efficient.The page loading speed and the neatness of the source code not only affect the user experience, but also have a subtle but important impact on search engine optimization (SEO).You may have encountered such a situation in the process of template development: although the template code looks neat, there are always some unwanted blank lines in the rendered HTML source code.

2025-11-09

How does AnQi CMS support displaying multilingual switch links and hreflang tags in the front-end template?

Today, with the increasing trend of globalization, many websites need to provide services to users from different countries and regions.This means that the website must not only support content display in multiple languages but also ensure that search engines can correctly identify these different language versions, thereby enhancing the visibility in the international market.AnQiCMS as a practical content management system provides strong and flexible support in this aspect.

2025-11-09

How to conditionally display elements in a template based on whether the content contains specific keywords?

In website operation, we often hope that the content can be presented more intelligently to visitors.For example, if a technical article mentions a specific product, we may want to automatically display the product's recommendation information at the top or side of the article;If the product description contains the phrase 'Limited Edition', we would like to add an eye-catching 'Limited' badge next to the product image.This ability to conditionally display elements based on whether the content contains specific keywords can greatly enhance the user experience and operational efficiency of the website.AnQiCMS as an efficient and flexible content management system

2025-11-09