In AnQiCMS template design, it is possible to flexibly control the display of content based on different conditions, which is the key to achieving website personalization and dynamic display.Whether it is based on whether there is a thumbnail in the article to decide whether to display the picture, or based on the user's role to display specific content, conditional logic can provide strong support.AnQiCMS uses a syntax similar to Django template engine, which makes it very easy for webmasters familiar with web development to get started.
Master the basic conditional logic in AnQiCMS templates
The conditional logic in AnQiCMS templates is mainly through{% if ... %}The tag is used to implement. The function of this tag is to determine whether a conditional expression is true (True), and if the condition is true, then executeifTags within the code block; if false (False), it will be skipped. All condition logic tags must appear in pairs to{% endif %}ensure the integrity of the template structure.
For example, you may want to display a variable (such as the title of an article) only when it exists, which can be written as follows:
{% if article.Title %}
<h1>{{ article.Title }}</h1>
{% endif %}
Here,article.TitleThis is a variable obtained from the backend. If it has a value, the title will be rendered.
Learn advanced usage of conditional logic
AnQiCMS templates' conditional logic is not just simpleifJudgment, it also supports more complex logic branches and a variety of operators, making content control more refined.
Multi-branch judgment:
elseandelifWhen your logic needs to handle scenarios such as 'if...then...else...' or 'if...then...else if...then...else...'elseandelifauto is used when (else if) abbreviation comes into play.else: whenifThe default code block executed when the condition is not met.elif: InifAfter,elseMultiple can be added before.elifTo check other conditions.
For example, you want to display an image based on whether the article has a thumbnail, and if not, display a piece of提示文字:
{% if item.Thumb %} <img src="{{ item.Thumb }}" alt="{{ item.Title }}" /> {% else %} <p>暂无图片</p> {% endif %}For example, display different greetings based on the user ID:
{% if user.Id == 1 %} <p>欢迎管理员!</p> {% elif user.Id > 0 %} <p>欢迎普通用户!</p> {% else %} <p>请登录!</p> {% endif %}Comparison operatorsIn conditional expressions, you can use common comparison operators to compare values:
==(Equal)!=(not equal to)>(Greater than)<(Less than)>=(Greater than or equal to)<=(Less than or equal to)
These operators can be used to compare numbers, strings, and even boolean values.
Logical operatorsTo build more complex conditions, you can use logical operators to combine multiple conditions:
andor&&(Logical AND): The entire expression is true only when all conditions are true.oror||(Logical OR): The entire expression is true when at least one condition is true.notor!(Logical NOT): Reverses the boolean value of the condition.
For example, an article is displayed only when it has both a title and content:
{% if article.Title and article.Content %} <h1>{{ article.Title }}</h1> <p>{{ article.Content }}</p> {% endif %}Or, when a category has subcategories or no documents, different links are displayed:
{% if item.HasChildren or item.ArchiveCount == 0 %} <a href="{{ item.Link }}">{{ item.Title }}(待补充)</a> {% else %} <a href="{{ item.Link }}">{{ item.Title }}</a> {% endif %}inOperatorinfilter-containFilter to implement similar functions.Assuming you have an article's
FlagProperties (such asFlag="h"Represents the headline), want to judge if it is a slide show (f) or recommended (c):{% if "f" in item.Flag or "c" in item.Flag %} <span class="badge">推荐</span> {% endif %}Or, if you have a string containing multiple keywords and want to check if a certain word is included:
{% set keywords_str = "SEO,网站优化,内容营销" %} {% if "SEO" in keywords_str %} <p>包含SEO关键词</p> {% endif %}
Common scenarios in practical applications
Understood these basic and advanced usage methods, let's see how conditional logic plays a role in actual scenarios in the AnQiCMS template:
Control the activation state of the navigation menuWhen creating a navigation menu, you usually want the currently visited page to be highlighted in the menu.
navListTag returnsitemContains in the objectIsCurrentField, it can be easily realized:{% navList navs %} {% for item in navs %} <li class="{% if item.IsCurrent %}active{% endif %}"> <a href="{{ item.Link }}">{{ item.Title }}</a> </li> {% endfor %} {% endnavList %}Handle the first/last element in the loopIn
forIn the loop, you can accessforloopVariable to get the current loop status. For example,forloop.CounterCan get the current loop index (starting from 1), which is very useful for adding special styles to the first element:{% archiveList archives with type="list" limit="10" %} {% for item in archives %} <div class="article-item {% if forloop.Counter == 1 %}featured{% endif %}"> <!-- 文章内容 --> </div> {% endfor %} {% endarchiveList %}Display content dynamically based on the field很多时候,某些内容字段可能为空,您不希望它们在前端显示。
- 文章描述If
Description为空,不显示其包裹的div.{% if item.Description %} <div>{{ item.Description }}</div> {% endif %} - Custom fields:如果您在后台模型中自定义了
authorField, only whenarchive.authorthere is a value, the author information will be displayed.{% archiveDetail archiveAuthor with name="author" %} {% if archiveAuthor %} <p>作者:{{ archiveAuthor }}</p> {% endif %}
- 文章描述If
display contact information or social media linksPass
contactLabel retrieval contact information, you can determine if a specific social media link exists before displaying the corresponding icon or link, to avoid displaying blank content: English{% contact contactFacebook with name="Facebook" %} {% if contactFacebook %} <a href="{{ contactFacebook }}" target="_blank">Facebook</a> {% endif %}
Optimize template code: Remove extra blank lines
When writing conditional logic, especially whenifThe statement does not contain any renderable content; it is only used to control the display of other tags. It may cause extra blank lines in the rendered HTML when used to control the display of other tags (such asif/forAn empty line produced, which is inside the tag start or end symbol, adding a hyphen-.
For example:
{%- if some_condition -%}
<p>这段内容会在满足条件时显示</p>
{%- endif -%}
In this example, evensome_conditionis false, the template engine will not leave an empty line in the HTML output{% if ... %}Any blank line inserted by the tag is very useful for keeping the generated HTML code neat.
Summary
AnQiCMS template conditional logic is a powerful tool for building dynamic and flexible websites. By proficiently usingif/else/elifCombine various comparison and logical operators, you can precisely control the display of each element on the page, thereby greatly enhancing the user experience and