NetLife Guru

Ternary Operator

The ternary operator is a compact conditional expression widely used in various programming languages, including in template systems like the one you're using. It provides a shorthand way of executing an expression based on a condition. In essence, it's a concise version of the if-else statement but used for assignments or direct output.

How It Works:

The basic syntax of the ternary operator is: `condition ? expression1 : expression2.`

Examples in Template Engine:

Standard Ternary Operation

    {$a = 1}
    {$b = 2}
    {$a==$b ? '$a & $b are equal': '$a & $b are not equal' }

Here, if $a equals $b, the string '$a & $b are equal' is returned, otherwise '$a & $b are not equal'.

Ternary Operation for Positive Condition Only

    {$a = 1}
    {$b = 2}
    {$a==$b ? '$a & $b are equal'}

This example checks if $a equals $b. If true, it returns '$a & $b are equal'. If false, it returns nothing or a default value if specified.


    {$a = 1}
    {$b = 1}
    {$a == $b ? <span class="bold">ok</span>}

In this case, if $a equals $b, HTML content (ok) is returned. This demonstrates the ternary operator’s versatility in handling not just text but also HTML elements.

Key Points:

This capability greatly enhances the expressiveness and functionality of your template engine, allowing for dynamic and responsive template creation.