企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# `if` The `if` statement in Twig is comparable with the if statements of PHP. In the simplest form you can use it to test if an expression evaluates to`true`: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>{% if online == false %} &lt;p&gt;Our website is in maintenance mode. Please, come back later.&lt;/p&gt; {% endif %} </pre></div></td></tr></table> You can also test if an array is not empty: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6 7</pre></div></td><td class="code"><div class="highlight"><pre>{% if users %} &lt;ul&gt; {% for user in users %} &lt;li&gt;{{ user.username|e }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} </pre></div></td></tr></table> Note If you want to test if the variable is defined, use `if users isdefined` instead. You can also use `not` to check for values that evaluate to `false`: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>{% if not user.subscribed %} &lt;p&gt;You are not subscribed to our mailing list.&lt;/p&gt; {% endif %} </pre></div></td></tr></table> For multiple conditions, `and` and `or` can be used: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>{% if temperature &gt; 18 and temperature &lt; 27 %} &lt;p&gt;It's a nice day for a walk in the park.&lt;/p&gt; {% endif %} </pre></div></td></tr></table> For multiple branches `elseif` and `else` can be used like in PHP. You canuse more complex `expressions` there too: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6 7</pre></div></td><td class="code"><div class="highlight"><pre>{% if kenny.sick %} Kenny is sick. {% elseif kenny.dead %} You killed Kenny! You bastard!!! {% else %} Kenny looks okay --- so far {% endif %} </pre></div></td></tr></table> Note The rules to determine if an expression is `true` or `false` are thesame as in PHP; here are the edge cases rules: | Value | Boolean evaluation | |-----|-----| | empty string | false | | numeric zero | false | | whitespace-only string | true | | empty array | false | | null | false | | non-empty array | true | | object | true |