NetLife Guru

Using variables

In your template engine, variables can be used and defined both within the templates and through the PHP code. Here’s how it works:

Using Predefined Variables

You can set variables using the `setVariables` method in PHP. These variables are then accessible within the template files. For example:


    $templateEngine->setVariables([
        'lang' => 'en',
        'title' => 'This is my title',
    ]);

In your template, you can use these variables as follows:


    {layout}
        {$lang}  // Outputs: en
        {$title}  // Outputs: This is my title
    {/layout}

Defining New Variables within Templates

You can also define new variables directly within your template files. Here’s how you can do it:


    {layout}
       // Defining a simple variable
       {$a = 1}
       {$b = 1}
       {$c = $a + $b}
       {$c}  // Output will be: 2

       // Defining an array
       {$arr = [0,1,2,3,4]}
       {$arr}  // Outputs the array
    {/layout}
Output:

        Output $c: 2
        Output $arr:
        [
          [0 => 0],
          [1 => 1],
          [2 => 2],
          [3 => 3],
          [4 => 4]
        ]

In this example, $a and $b are simple variables, while $arr is an array. The will output the sum of $a and $b, and will output the array structure.

This flexibility allows for dynamic content creation within templates, enhancing the possibilities for customizing the output based on various conditions or inputs.