As an experienced website operations expert, I am well aware of the importance of a flexible and powerful template system for content management.AnQiCMS takes advantage of its high-performance architecture based on the Go language and its support for Django template engine syntax, providing us with great convenience.It is not just a tool for publishing content, but also a tool for us to achieve personalized content display and improve user experience.
In the world of AnQiCMS templates,ifandforTags are undoubtedly the cornerstone of building dynamic content. They endow templates with the ability to make logical judgments and iterate in loops, allowing our website content to present intelligently based on different conditions or to display a series of related data in a neat and orderly manner.Today, let's delve deeply into how to cleverly use these tags in the AnQiCMS template to inject more vitality into your website.
I. The Art of Logic:ifFlexible use of tags
In website operation, we often need to display different content according to different business scenarios or data states.For example, when the user logs in, a welcome message is displayed, and when not logged in, a registration/login entry is displayed;Or add special style markers based on the article's 'recommended' attribute. At this point,ifTags have become the core tool for us to make conditional judgments.
AnQiCMS'ifThe tag syntax is concise and clear, similar to many modern template engines, and it supports single conditional judgments, withelsebinary choice judgments, as well as withelifConditional judgment of 'else if'. AllifAll statements must end with{% endif %}end.
1. Basic condition judgment:{% if 条件 %}
This is the simplest form, whenifthe following conditions are true (trueWhen, the content inside the tag will be rendered.
{# 假设我们想判断网站名称是否存在,存在则显示 #}
{% if system.SiteName %}
<h1>欢迎来到 {{ system.SiteName }}!</h1>
{% endif %}
You can use various comparison operators(==equal,!=Not equal to,>Greater than,<Less than,>=Greater than or equal to,<=less than or equal to), as well as logical operators(andand,oror,notNot) to construct complex conditions. For example, to judge whether the document ID is 10:
{% if archive.Id == 10 %}
<p>这是文档ID为10的特别内容。</p>
{% endif %}
2. Binary choice judgment:{% if 条件 %} ... {% else %} ... {% endif %}
When the condition is true, execute some code, otherwise execute another part. This is very useful in handling scenarios with clear 'yes' and 'no' results.
{# 判断文章是否有缩略图,有则显示,无则显示占位图 #}
{% if archive.Thumb %}
<img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
<img src="/public/static/images/placeholder.webp" alt="无图片">
{% endif %}
3. Multi-condition judgment:{% if 条件 %} ... {% elif 其他条件 %} ... {% else %} ... {% endif %}
When you need to handle two or more mutually exclusive conditions,eliftags come in handy. They allow you to add multiple judgment branches in a chain.
{# 根据文档的 Flag 属性显示不同的标签 #}
{% if archive.Flag contains "h" %}
<span class="badge badge-hot">头条</span>
{% elif archive.Flag contains "c" %}
<span class="badge badge-recommend">推荐</span>
{% else %}
<span class="badge badge-normal">普通</span>
{% endif %}
In this example,archive.Flag contains "h"Will judgeFlagDoes the string contain the character 'h', if it does, then execute the first segment of code, otherwise continue the judgmentelifcondition.
4. Check if the variable exists or is empty:
ifTags can naturally be used to check if a variable exists or if its value is empty (for examplenilsuch as empty strings, empty arrays, etc.).
{# 检查联系电话是否存在 #}
{% if contact.Cellphone %}
<p>联系电话:{{ contact.Cellphone }}</p>
{% else %}
<p>暂无联系电话</p>
{% endif %}
Second, the power of iteration:forThe magic of tag iteration
A dynamic website's core feature is its ability to display a series of repetitive but different content, such as article lists, product lists, navigation menu items, comment lists, and so on.forThe label is the key to implementing this "loop iteration" function in the AnQiCMS template engine.It allows us to easily access each element in an array, slice (slice), or other iterable object and render it for each element.
1. Basic loop traversal:{% for item in collection %}
This isforThe most common usage of the tag, it will traverseinthe collection behind (collection), assigning each element in turn toitemvariables and displayed in{% endfor %}the previous code block for rendering.
{# 遍历并显示最新的10篇文章标题和链接 #}
{% archiveList archives with type="list" limit="10" %}
<ul>
{% for article in archives %}
<li>
<a href="{{ article.Link }}">{{ article.Title }}</a>
</li>
{% endfor %}
</ul>
{% endarchiveList %}
here,archiveListThe tag obtained a document list and assigned it toarchivesthe variable. Then,forLoop througharchiveseacharticlethe object, and rendered the article title and link.
2. Handle empty set:{% for item in collection %} ... {% empty %} ... {% endfor %}
In the actual operation, we often encounter the situation where a list may be empty.If you loop an empty list directly, nothing will be displayed on the page, which may confuse the user.AnQiCMS offorThe tag provided a very elegantemptySubtags are used to handle this situation. WhencollectionIf it is empty or does not exist,{% empty %}and{% endfor %}The content between them will be rendered.
{# 遍历并显示 Tag 文档列表,如果为空则显示提示信息 #}
{% tagDataList archives with type="page" limit="10" %}
{% for item in archives %}
<div class="tag-article">
<h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
<p>{{ item.Description|truncatechars:100 }}</p>
</div>
{% empty %}
<p class="no-content">当前标签下暂无相关文章。</p>
{% endfor %}
{% endtagDataList %}
UseemptyThan first usingifJudging the length of the list first makes the loop more concise and also conforms to the logical flow of the code.
3. Loop context variable: Gives more control to iteration.
InforInside the loop, AnQiCMS provides a series of built-inforloopvariables to help us better control the rendering behavior of the loop:
forloop.Counter: The current iteration number of the loop (starting from 1).forloop.Revcounter: The remaining number of iterations in the loop (counting down from the total).forloop.First: If it is the first element in the loop, it is.true.forloop.Last: If it is the last element in the loop, it is.true.forloop.OddIfCounteris an odd number, istrue.forloop.EvenIfCounteris an even number, istrue.
These variables are very useful when adding special styles to list items (such as highlighting the first one, alternating row colors), or inserting additional content at specific positions.
`twig {# Utilizing forloop variable, add different styles or content to list items #} {% categoryList categories with moduleId=“1” parentId=“0” limit=“5” %}
<ul class="category-nav">
{% for category in categories %}
<li class="{% if forloop.First %}first-item{% endif %} {% if forloop.Last %}last-item{% endif %} {% if forloop.Odd %}odd-row{% else %}even-row{% endif %}">
第 {{ forloop.Counter }} 项:<a href="{{ category.Link }}">{{ category.Title }}</a>
{% if forloop.Last %}
<span class="tip">(这是最后一项)</span>
{% endif %}
</li>
{% endfor %}
</ul>
{% end