In AnQiCMS template development, we often encounter situations where we need to display different content based on different conditions. Beginners may tend to use a lot of{% if 条件 %}The statement, as the project requirements grow, these conditional judgments are nested layer by layer, and it will soon make the template difficult to read, maintain, and even hide potential logical errors.Once code readability decreases, not only will the development efficiency be affected, but the future feature iteration and problem troubleshooting will also become extremely difficult.
幸运的是,AnQiCMS is based on a Go language Django-like template engine that provides rich features, and we can use these tools to effectively avoid ifOverly nested statements make template code clear and elegant.
1. Use wiselysetandwithDeclare variables, preprocess complex conditions
ReduceifThe first step in nesting is to simplify the condition itself. When the condition expression is complex or needs to be used multiple times, we can store the result in a variable in advance.AnQiCMS template support{% set 变量名 = 值 %}and{% with 变量名 = 值 %}Define variables in two ways.
For example, if you need to determine whether a document is recommended, pinned, and belongs to a specific category, the traditional way might be something like this:
{% if archive.Flag contains "c" and archive.Flag contains "h" and archive.CategoryId == 10 %}
{# 展示推荐置顶文章的特殊样式 #}
{% else %}
{# 普通文章样式 #}
{% endif %}
Such conditions are long and difficult to see at a glance. We can divide them bysetorwith:
{% set isSpecialRecommend = archive.Flag contains "c" and archive.Flag contains "h" and archive.CategoryId == 10 %}
{% if isSpecialRecommend %}
{# 展示推荐置顶文章的特殊样式 #}
{% else %}
{# 普通文章样式 #}
{% endif %}
Thus,ifThe condition of the statement becomes clear and concise.setThe declared variables are valid within the current module, andwithis typically used to define multiple variables temporarily, and it needs to be{% endwith %}end. Properly using variable declarations can effectively improve the clarity of conditional judgments.
Second, use filters to simplify condition judgment and data display
AnQiCMS provides rich filters (Filters) that can process variables in various ways, often replacing simpleif/elselogic.
defaultFilter:When a variable may be empty, provide a default value to avoid long-windedness.if/else.{# 避免:{% if archive.Description %}{{ archive.Description }}{% else %}暂无描述{% endif %} #} {{ archive.Description|default:"暂无描述" }}yesnoFilter:Used to handle boolean values, outputting specified text based on truth or falsity.{# 假设 archive.IsPublished 是一个布尔值 #} {{ archive.IsPublished|yesno:"已发布,草稿,未知" }}lengthOr simply judge directly: Check if lists, strings, and objects are empty to avoid{% if list|length > 0 %}.AnQiCMS's template engine is similar to Django and can be used directly
{% if 变量 %}Check if a set or string is non-empty.{# 避免:{% if tags|length > 0 %} #} {% if tags %} {# 标签列表不为空时 #} {% endif %}containFilter:Quickly determine if a string or array contains a specific keyword without manual traversal or complex string functions.{% if archive.Flag|contain:"c" %} {# 判断是否包含“推荐”标记 #} <span>推荐</span> {% endif %}
Through these filters, many simple condition judgments and data formatting can be completed directly when the variable is output, and there will be fewer blocks in the template.ifBlocks.
Chapter 3, Modular Templates, Embraceincludeandmacro
When a complexifWhen a branch contains a large amount of content, even if the condition itself is clear, the entire template size will become large. At this point, modularization is**practice.
includeTags:Extract the common parts of the template or complex branch logic into a separate file.For example, if your article detail page varies according to
FlagThere are multiple display modes for properties, you can organize them in this way:{% if archive.Flag contains "f" %} {# 幻灯模式 #} {% include "partial/archive_layout_slideshow.html" with article=archive %} {% elif archive.Flag contains "a" %} {# 特荐模式 #} {% include "partial/archive_layout_featured.html" with article=archive %} {% else %} {# 默认模式 #} {% include "partial/archive_layout_default.html" with article=archive %} {% endif %}Each
partial/archive_layout_*.htmlThe file is responsible for rendering its own specific layout, while the main template remains simple.with article=archiveAllows you to pass specific variables to the included template, avoiding global pollution and making the module more independent and reusable.macroMacro definition:For a short segment of HTML structure that needs to be reused in multiple places and has specific logic, you can usemacro. Macros can receive parameters like functions and encapsulate internal logic.Suppose you need to display an article card with a thumbnail and title on multiple list pages, and the style may vary depending on whether there is a thumbnail:
"`twig {# In archive.helper.html define macro #} {% macro render_article_card(article) %}
{% if article.Thumb %} <img src="{{ article.Thumb }}" alt="{{ article.Title }}"> {% endif %} <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3> <p>{{ article.Description|