Core

Conditional Logic

Conditional logic lets a template render different markup based on the current value or expression.

Check A Value#

Use {{ if }} when markup should be conditional:

phpresources/views/front-page.php
{{ query:posts }}  <article>    <h2><a href="{{ url }}">{{ title }}</a></h2>    {{ if excerpt }}      <p>{{ excerpt }}</p>    {{ /if }}  </article>{{ /query:posts }}

{{ if excerpt }} checks whether the current post has an excerpt.

Use Else#

Use {{ else }} for fallback markup:

php
{{ if excerpt }}  <p>{{ excerpt }}</p>{{ else }}  <p>No excerpt yet.</p>{{ /if }}

The closing tag is always {{ /if }}.

Use Else If#

Use {{ else if }} when there is more than one condition:

php
{{ if auth_action == "lost-password" }}  <h1>Reset your password</h1>{{ else if auth_action == "register" }}  <h1>Create an account</h1>{{ else }}  <h1>Sign in</h1>{{ /if }}

TemplateX checks the branches from top to bottom and renders the first branch that matches.

Compare Values#

Use comparisons when a value must match something specific:

php
{{ if collection == "post" }}  <p>This is a blog post.</p>{{ /if }}

Common comparison operators are:

  • == equals
  • != does not equal
  • > greater than
  • >= greater than or equal to
  • < less than
  • <= less than or equal to

Combine Conditions#

Use && when both values must be true:

php
{{ if featured && excerpt }}  <p>{{ excerpt }}</p>{{ /if }}

Use || when either value can be true:

php
{{ if is_current || is_parent }}  <span>Active</span>{{ /if }}

Use ! to reverse a condition:

php
{{ if !excerpt }}  <p>No excerpt yet.</p>{{ /if }}

Use parentheses when the grouping should be clear:

php
{{ if featured && (excerpt || content) }}  <p>Featured content</p>{{ /if }}

Ternary#

Use ternary expressions for small inline choices:

php
<span>{{ featured ? 'Featured' : 'Regular' }}</span>

That reads as: if featured is true, print Featured; otherwise print Regular.

Use && when you only need to print something when a condition is true:

php
<a class="post-link {{ is_current && 'is-current' }}" href="{{ url }}">  {{ title }}</a>

When one class should apply to either of two conditions, group the conditions first:

php
<a class="{{ (is_current || is_parent) && 'is-current' }}" href="/dames">  Dames</a>

Use || when you want a fallback value:

php
<p>{{ excerpt || 'No excerpt yet.' }}</p>

The full ternary form is condition ? value : fallback. Use &&, not a single &.

Inline Markup Shorthand#

For one small element, && can also guard a markup fragment:

php
{{ sale_price && <p class="price-compare">{{ regular_price | currency }}</p> }}

That renders the <p> only when sale_price has a value. TemplateX still parses the markup inside the fragment, so nested value tags and modifiers work normally.

Use block conditions for larger chunks of markup:

php
{{ if sale_price }}  <p class="price-compare">{{ regular_price | currency }}</p>{{ /if }}

Use ternary expressions for small text or class changes.