As an experienced website operations expert, I know how crucial precise control of template logic is when building and maintaining an efficient, user-friendly website.Especially when using content management systems like AnQiCMS, which is based on Go language and emphasizes performance and flexibility, being able to flexibly judge the status of variables and execute conditional logic according to different situations is the foundation for ensuring correct content display, avoiding page errors, and improving user experience.
The template engine of AnQi CMS adopts a marking method similar to Django syntax, which allows operators and developers familiar with web development to quickly get started.It provides intuitive and powerful conditional judgment and loop control capabilities, helping us easily deal with various content display scenarios.Today, let's delve into how to judge if a variable is empty or execute complex conditional logic in AnQiCMS templates.
Basic conditional judgment in AnQiCMS templates:ifThe magic use of tags
In the template world of AnQiCMS, the most core condition judgment tool is undoubtedly{% if %}Tag. Its syntax is concise and powerful, allowing us to decide whether to render a specific content block based on the boolean value of a variable.
A variable in AnQiCMS template engine, when it isnil(empty value),false(boolean false), number0An empty string""When it is empty (such as an empty array, empty slice, or empty dictionary/map), it will be{% if %}labeled as 'false' (falsy). This means we do not need to explicitly write{% if variable == nil %}or{% if variable == "" %}and use directly{% if variable %}Can very elegantly judge whether a variable has actual content.
Let's look at some common examples to understand this:
Judging whether a string is empty:
{% if archive.Title %} <h1>{{ archive.Title }}</h1> {% else %} <h1>暂无标题</h1> {% endif %}Here, if
archive.TitleIf any non-empty string value exists, the title will be displayed; otherwise, 'No title' will be shown.Determine if a list or set is empty:Assume
category.Imagesis a list of images:{% if category.Images %} <div class="banner"> {% for img in category.Images %} <img src="{{ img }}" alt="分类图片"> {% endfor %} </div> {% else %} <p>此分类暂无图片展示。</p> {% endif %}If
category.ImagesContains an image, which will be rendered; if it is an empty list, a prompt message will be displayed.Evaluate boolean or numeric values:For example, obtain whether the website is in a closed state from the background system settings:
{% if system.SiteStatus == 0 %} {# 假设0代表开启,非0代表闭站 #} <p>网站正在正常运行。</p> {% else %} <p>网站已暂停访问:{{ system.SiteCloseTips }}</p> {% endif %}We can also utilize
{% elif %}(else if) and{% else %}Build more complex conditional chains to deal with multiple business logic:{% if user.IsVIP %} <p>欢迎VIP会员,尊享专属内容!</p> {% elif user.TotalReward > 100 %} <p>您的累计收益已超过100元,快升级VIP解锁更多权益!</p> {% else %} <p>您是普通会员,查看更多精彩内容!</p> {% endif %}
Gracefully handle empty sets:forLoopingemptytags
When dealing with list, array and other collection data, we often need to determine if they contain elements.If the collection is empty, we may need to display a prompt saying 'No content available'.{% for %}Loops provide a very practical{% empty %}Tags make the handling of this scene particularly concise and elegant.
For example, when we need to display a list of related articles for a document:
{% archiveList archives with type="related" limit="5" %}
<div class="related-articles">
<h3>相关推荐</h3>
<ul>
{% for item in archives %}
<li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
{% empty %}
<li>暂无相关文章推荐。</li>
{% endfor %}
</ul>
</div>
{% endarchiveList %}
IfarchivesThe list contains articles,{% for %}The loop will traverse and display them normally; if the list is empty,{% empty %}the content within the tags will be rendered, perfectly avoiding any additional{% if archives %}Judgment. This not only makes the template code more concise, but also improves the robustness of the website.
Smart use of filters: provide default values for variables or perform advanced judgments
The template filters (Filters) of AnQiCMS are powerful tools for processing variables and formatting output, some of which are particularly useful for judging variable states or providing alternative content.
defaultanddefault_if_noneFilter: Provide alternative contentWhen a variable may be empty or not exist, we would like to provide a default value to replace it, rather than letting the page display a blank or an error.defaultThe filter provides a default value when the variable is evaluated as 'false' (such as an empty string, 0, false).default_if_noneThe filter is more strict, only when the variable is indeednil(or in Go language,nilAn example value when a default is provided only when the type is specified, and it does not apply to empty strings or 0.
For example, display the article description, and if it is empty, display 'Click to view details':
<p>{{ archive.Description|default:"点击查看详情" }}</p>If
archive.DescriptionFor empty strings ornilIt will display “Click to view details”.Assume
user.Phonecan be anilfield, not an empty string:<p>联系电话:{{ user.Phone|default_if_none:"未提供" }}</p>lengthFilter: Check the length of a string or a collectionlengthThe filter can conveniently obtain the number of characters in a string or the number of elements in a collection (such as an array, slice, or map).This is very useful when it is necessary to judge the length precisely rather than just 'true or false'.{% if archive.Content|length > 100 %} <p>文章内容很长,请耐心阅读。</p> {% else %} <p>文章内容较短。</p> {% endif %}Here, we judge whether the length of the article content string exceeds 100 characters.
containFilter: Determine if it contains specific contentIf you need to determine whether a string contains a substring, or whether an array contains an element,containThe filter can be used.{% if archive.Content|contain:"SEO" %} <p class="tag">本文包含SEO相关内容。</p> {% endif %}If the word 'SEO' is included in the article content, the corresponding prompt will be displayed.
yesnoFilter: Semantic boolean outputyesnoThe filter can convert boolean values or variables that can be evaluated as boolean values into more semantically meaningful text output.It can accept up to three parameters, which correspond to the display text for 'true', 'false', and 'unknown/null', respectively.<p>审核状态:{{ archive.Status|yesno:"已发布,待审核,未设置" }}</p>If
archive.Statusresponse fortrue(e.g. 1), display 'Published'; forfalse[For example 0], display 'Pending Review' if it is true.nilIf it is not, display 'Not Set'.
Practical Exercise: Comprehensive Application of Judgment Logic
Let us demonstrate how to comprehensively apply these judgmental logic by using a slightly more complex scenario. Suppose we are building a product detail page that needs to display content based on different product attributes:
`twig
<h1>{{ archive.Title|default:"产品名称待定" }}</h1>
{%- if archive.Logo %}
<div class="product-image">
<img src="{{ archive.Logo }}" alt="{{ archive.Title }}">
</div>
{%- elif archive.Images %}
<div class="product-gallery">
{%- for img in archive.Images %}
<img src="{{ img }}" alt="产品图">
{%- empty %}
<p>产品图片正在上传中...</p>
{%- endfor %}
</div>
{%- else %}
<div class="no-image-placeholder">
<p>暂无产品图片。</p>
</div>
{%- endif %}
<div class="product-