How to debug variables in a template and display their structure and values?

Calendar 👁️ 63

During the development and maintenance of website templates, we often encounter such situations: some page elements do not display as expected, or data seems missing or incorrectly formatted.This is the key to quickly locate the problem when you can clearly see the structure and specific values of the variables in the template.For users who use AnQiCMS, the system provides powerful and convenient debugging tools to help us easily "penetrate" the template data.

Why do you need to debug template variables?

In AnQiCMS templates, data is passed through variables. These variables may come from system configuration, article content, category information, or within the template itself through various tags (such asarchiveList/categoryDetail)Dynamically retrieved. When the page rendering fails, directly check the actual values and data structures of these variables can help us:

  1. Confirm if the data exists:Did the variable successfully retrieve the data?
  2. Verify the content of the data:Is the retrieved data the expected content?
  3. Understand the data structure:If a variable is a complex object or list, what fields does it contain? Are the field names correct?

Mastering variable debugging techniques can significantly improve our efficiency in solving template problems.

Core tool:dumpFilter

AnQiCMS's template engine supports a rich set of filters, and the most direct and powerful variable debugging tool isdumpfilter.dumpThe filter can output the complete data structure and current value of any variable in a clear and readable format.

Usage:

You just need to add it after any variable you want to check.|dump.

{# 检查整个 archives 变量的结构和值 #}
{{ archives|dump }}

{# 检查单个 item 变量的结构和值 #}
{{ item|dump }}

When you add this code to the template and refresh the page, it will output something like the following (depending on the type of variable):

&models.Archive{Id:1, Title:"我的第一篇文章", Description:"这是一篇测试文章。", CreatedTime:1678886400, ...}

This output clearly showsitemIs amodels.ArchiveThe type of object, which lists all its fields (such asId,Title,Description,CreatedTimeetc.) and their current values. This is crucial for understanding the data object structure passed to the template by the system.

Understanding Data Structures and Delving Deep

dumpThe filter can display the full picture of variables at once, but in actual debugging, we often need to combine our understanding of different data types with some auxiliary skills.

  1. Basic variables (strings, numbers, booleans):Use variables directly for simple cases{{ 变量名 }}You can view its value. If it is blank, it may mean that the variable is undefined or the value is null.

  2. Object (struct) properties:Most of the data in AnQiCMS (such as articles, categories, users, etc.) is passed in the form of structured objects. If you know the variable throughdumpa filterarchiveis an article object, and it has aTitleproperty, you can access it directly through{{ archive.Title }}to view the article title.

  3. lists and arrays:When a variable is a list or array containing multiple elements (for examplearchiveListreturnedarchives),we need to use{% for %}a loop to iterate over each element. Inside the loop, each element is used todumpFilter:

    {% archiveList articles with type="list" limit="3" %}
        {% for article in articles %}
            {# 在循环内部,检查每个 article 对象的结构和值 #}
            {{ article|dump }}
            <h3>{{ article.Title }}</h3>
            <p>{{ article.Description }}</p>
        {% endfor %}
    {% endarchiveList %}
    

    Thus, you can check each article object in the list one by one to ensure its data integrity and correctness.

  4. Process HTML content:safeFilterWhile debugging article content(archive.Content) or classification description(category.DescriptionWhen this variable may contain HTML tags, you might find that the output is the HTML source code rather than the rendered content.This is because the AnQiCMS template engine, for safety (to prevent XSS attacks), defaults to escaping all variable outputs.To correctly display HTML content, you need to usesafeFilter:

    {# 确保文章内容被正确渲染为 HTML #}
    <div>{{ archive.Content|safe }}</div>
    

    If you are debugging, thendumpThe content includes HTML tags but is output directly{{ archive.Content }}But what you see is the source code, then|safeThat is the solution you need.

Practical skills and application scenarios

exceptdumpandsafeFilter, along with some practical tips to make your debugging process more efficient:

  • Isolation and focus: use{% set %}or{% with %}When you need to debug a deeply nested or computationally generated variable, you can use{% set %}or{% with %}Label it to extract it into a temporary variable for easier checking.

    {% set myArticle = archives|first %} {# 获取列表的第一个元素并赋值给 myArticle #}
    {{ myArticle|dump }} {# 调试这个临时变量 #}
    
    {% with debugTitle = archive.Title %}
        <p>调试标题: {{ debugTitle }}</p>
    {% endwith %}
    
  • Check if the variable exists:{% if %}Before trying to output a variable, use first{% if 变量名 %}Judging is a good habit. This can avoid template rendering errors caused by variables being empty or not existing, especially when debugging variables that may occasionally be empty.

    {% if archive.Author %}
        <p>作者:{{ archive.Author }}</p>
    {% else %}
        <p>作者信息缺失。</p>
    {% endif %}
    
  • Output a specific attribute:IfdumpThe information output is too much, you just want to quickly confirm a specific attribute (such as the article'sLink), output directly{{ item.Link }}会比dumpthe wholeitemMore concise.

  • Temporary comment code:{# #}or{% comment %}During debugging, it is often necessary to temporarily disable some code blocks. Use{# 这是单行注释 #}or{% comment %} 这里可以注释多行代码 {% endcomment %}It can avoid the trouble of deleting and restoring code.

  • Combine with other filters:

    • |length:Check the length of a list or string. For example{{ archives|length }}It can tell you how many articles are in the list.
    • |join:Concatenate the elements of an array or list with a specified delimiter into a string to view all elements. For example{{ categories|join:", "|safe }}.
    • |stringformat:Format numbers and strings, especially useful when precise control over the number of digits displayed is needed.

Case demonstration: InsightarchiveListof the data

Suppose you are developing a list page of articles, but the page does not display any articles or the article titles are incorrect.

Your template code might look like this:

{% archiveList articles with type="page" limit="10" %}
    {% for post in articles %}
        <div class="article-item">
            <h2><a href="{{ post.Link }}">{{ post.Title }}</a></h2>
            <p>{{ post.Description }}</p>
        </div>
    {% empty %}
        <p>目前还没有文章。</p>
    {% endfor %}
{% endarchiveList %}

Debugging steps:

  1. Check if the entire list variable exists and has the correct structure:In{% archiveList %}After the tag, but before{% for %}Insert before the loop{{ articles|dump }}.

    {% archiveList articles with type="page" limit="10" %}
        {{ articles|dump }} {# 临时插入这行 #}
        {% for post in articles %}
            {# ... #}
        {% endfor %}
    {% endarchiveList %}
    

    Refresh the page and viewarticlesIf there is any data.dumpAn empty output or no output at all indicatesarchiveListThe label may not have retrieved the data (checktype/limit/categoryIdWhether the parameters are correct), orarticlesThe variable name is incorrect.

  2. Check the structure of individual list elements:IfarticlesThe variable has data but inside the looppost.Titleorpost.LinkIf it's not right, then willdumpFilter

Related articles

How to remove extra spaces or characters from a string before displaying content?

During the operation of a website, we often encounter unnecessary spaces, line breaks, or special characters in the content. These 'impurities' not only affect the appearance of the content and the user's reading experience, but may also have a negative impact on the layout of the page and search engine optimization (SEO).AnQiCMS (AnQiCMS) is an efficient content management system that provides flexible and powerful template functions, among which the built-in template filters are the tools to solve such problems.Before you display content on the page, clean the string

2025-11-08

How to concatenate or replace strings before displaying them?

In AnQiCMS (AnQiCMS) content operation, we often encounter the need to dynamically process strings displayed on the front end of the website.To enhance the user reading experience, optimize search engine inclusion, or maintain consistency in content display, flexibly concatenating or replacing strings is a very practical skill.AnQi CMS, with its efficient template engine based on Go language, provides us with powerful and convenient tools, making these operations easy to implement at the template level.String concatenation

2025-11-08

How to format floating-point numbers, controlling the number of decimal places displayed?

Website content operation, it is crucial to display numbers accurately, especially floating-point numbers such as prices and statistics, for enhancing user trust and page professionalism.AnQi CMS knows this, providing simple and flexible tools in its powerful template engine, allowing content creators to easily control the display format of floating-point numbers, including decimal places, without delving into complex programming.Next, we will discuss how to use built-in filters in Anqi CMS templates to elegantly format floating-point numbers.### Use `floatformat`

2025-11-08

How to truncate long text and display an ellipsis?

In website content presentation, we often need to refine some long text content, such as displaying abstracts on article list pages or showing brief descriptions on product cards.If the entire content is displayed directly, it may not only destroy the neat layout of the page, but may also affect the efficiency of users in quickly browsing information.Therefore, truncating long text and adding an ellipsis at the end has become a common strategy to improve user experience.AnQi CMS as an efficient content management system, built-in flexible template filters, can help us easily achieve this function

2025-11-08

How to convert the original image address to a thumbnail address for display?

In modern website operations, images play a crucial role, not only enhancing the attractiveness of the content but also effectively conveying information.However, very large image files can significantly slow down website loading speed, harm user experience, and even affect search engine rankings.Therefore, converting the original image address to an optimized thumbnail address for display is an important part of website performance optimization.AnQiCMS as an efficient content management system fully considers the needs of image processing, built-in powerful thumbnail generation and management functions.Configure and template calls reasonably

2025-11-08

How to customize the layout and content display of the article detail page in AnQi CMS?

AnQiCMS (AnQiCMS) is a highly flexible content management system that provides great freedom to content operators, especially in customizing the layout and content display of article detail pages.Understanding the underlying mechanism and operation methods can help us better create personalized pages that meet user needs and optimize SEO performance.Why do you need a custom article detail page?In website operation, the article detail page is not only a carrier of content, but also a key touchpoint for users to deeply interact with information and achieve conversion goals.The standardized template is convenient and fast

2025-11-08

How to use the `archiveList` tag to display the latest 10 article titles and summaries on the homepage?

In Anqi CMS, the homepage often plays a crucial role in displaying the latest content and attracting visitors' attention.If you want to clearly list the latest 10 article titles and summaries on the homepage, the `archiveList` tag is the powerful tool to achieve this goal.It is flexible and easy to use, helping you easily display dynamic content in the most prominent position on the website.We need to display the titles and summaries of the latest 10 articles on the homepage by using the `archiveList` tag's core parameters

2025-11-08

How to call and display product custom parameters (such as price, stock) on the product detail page?

In website operation, especially for product display websites, product details are far more than just titles and descriptions.In order to better meet user needs, it is particularly important to display various personalized parameters such as product price, inventory, color, material, and so on.AnQiCMS (AnQiCMS) takes advantage of its flexible content model and powerful template tag features, allowing you to easily call and display these custom parameters on product detail pages.### Preparations: Define Product Custom Parameters To display custom parameters on the product detail page, you first need to define these parameters in the AnQi CMS backend

2025-11-08