NetLife Guru

Control Structures in the Template Engine

`if`, `else if`, `else`

The `if`, `else if`, `else` control structures in the template engine provide a powerful way to control the flow of rendering based on conditions. This flexibility is key in creating dynamic templates that respond to varying data conditions.


    {layout}
        {$a = "1"}
        {$b = "1"}
        {$c = "2"}

        {if $a == $b}
            $a is equal to $b
        {else if $a == $c}
            $a is equal to $c
        {else}
            $a is not equal to $b nor $c
        {/if}
    {/layout}

The proper closure of these blocks with {/if} is crucial for the correct functioning of the template logic.

Foreach

foreach in this template engine is especially useful for iterating over arrays and objects. It's used to loop through each element in a collection, rendering HTML or other template code for each item.


    {layout}
        {$arr = [0 => "A", 1 => "B", 2 => "C"]}

        <ul>
        {foreach $arr as $key => $value}
            <li>Key: {$key} Value: {$value}</li>
        {/foreach}
        </ul>
    {/layout}

In summary, these control structures bring logical and iterative processing capabilities into the templating engine, akin to standard PHP, but with a syntax that is streamlined for template design. They play a vital role in building templates that are both dynamic and efficient in responding to different data scenarios