@if

Display content based on dynamic conditions

Conditional statements in Elements allow you to control when content is displayed based on certain conditions. Using @if, @elseif, and @else, you can define different outcomes depending on the values of variables. This is useful for showing or hiding content based on user settings, mode (edit or preview), or other dynamic conditions.

Syntax

@if(condition)
    <!-- Content shown when condition is true -->
@endif

With else if and else branches:

@if(condition)
    <!-- Content for first condition -->
@elseif(otherCondition)
    <!-- Content for second condition -->
@else
    <!-- Fallback content -->
@endif

Block-Level Conditionals

Basic If Statement

Display content when a switch or boolean property is true:

If Not Statement

Use the ! operator to check if something is false:

Multiple Conditions with Else If

Chain multiple conditions before falling back to else:

Edit/Preview Mode Detection

Elements provides built-in edit and preview variables:

Inline Conditionals

Conditionals can also be used inline within HTML attributes. This is particularly useful for dynamic class names and attribute values.

Dynamic Class Names

Apply classes conditionally based on properties:

Multiple Conditional Classes

Chain multiple inline conditions for complex class logic:

Conditional Attributes

Add or remove attributes based on conditions:

Conditional Image Attributes

Apply different behaviors based on settings:

Conditional Visibility Styles

Hide elements in preview/published mode:

Nested Conditionals

Conditionals can be nested for complex logic:

Combining with @each

Use conditionals within loops for filtered rendering:

Common Patterns

Fallback Content

Show a placeholder when no content exists:

Feature Toggles

Enable or disable component features:

Conditional Includes

For conditional template includes, consider using @includeIf for cleaner syntax:

Best Practices

  1. Keep conditions simple - For complex logic like string comparisons, use the hooks file to compute boolean values and pass them to the template.

  2. Use meaningful property names - Boolean properties should have clear names like showIcon, enableLazyLoading, or hasImage.

  3. Prefer @includeIf for conditional includes - Instead of wrapping @include in @if, use @includeIf for cleaner templates.

  4. Only non-responsive controls work in conditionals - Responsive controls cannot be used directly in @if statements.

Last updated

Was this helpful?