3. Passing variables to templates

We have seen in 2. Hello World! how to create a static template. Let’s send some variables to have a more dynamic display.

src/Controller/MyModuleController.php
 1<?php
 2
 3namespace MyCompany\iTop\MyModule\Controller;
 4use Combodo\iTop\Application\TwigBase\Controller\Controller;
 5use UserRights;
 6
 7class MyModuleController extends Controller
 8{
 9    public function OperationHelloWorld()
10    {
11        $aParams['sName'] = UserRights::GetUser();
12        $aParams['sDate'] = date("r");
13        $this->DisplayPage($aParams);
14    }
15}

The DisplayPage() method accept an array of parameters. This array is transformed into variables for the Twig template.

Here two variables are created: sName and sDate, we can use them in the template.

templates/HelloWorld.html.twig
1{% UITitle ForPage {sTitle:'Hello ' ~ sName ~ '!'} %}{% EndUITitle %}
2{% UIContentBlock Standard {DataAttributes: {role: 'date'}} %}
3    We are currently {{ sDate }}
4{% EndUIContentBlock %}

The output is then

../../_images/Hello2.png

The variables can be of any type, for example you can give an array as a variable:

src/Controller/MyModuleController.php
 1<?php
 2
 3namespace MyCompany\iTop\MyModule\Controller;
 4use Combodo\iTop\Application\TwigBase\Controller\Controller;
 5use UserRights;
 6
 7class MyModuleController extends Controller
 8{
 9    public function OperationHelloWorld()
10    {
11        $aParams['sName'] = UserRights::GetUser();
12        $aParams['sDate'] = date("r");
13        $aParams['aQuarter'] = ['January', 'February', 'March'];
14        $this->DisplayPage($aParams);
15    }
16}

Here aQuarter is an array containing some months, we can use it in a selector:

templates/HelloWorld.html.twig
 1{% UITitle ForPage {sTitle:'Hello ' ~ sName ~ '!'} %}{% EndUITitle %}
 2{% UIContentBlock Standard {DataAttributes: {role: 'date'}} %}
 3    We are currently {{ sDate }}
 4{% EndUIContentBlock %}
 5
 6{% UIForm Standard {sId:'my-form'} %}
 7    Select Month:
 8    {% UISelect ForSelect {sName:'month'} %}
 9        {% for index,sMonth in aQuarter %}
10            {% UISelectOption ForSelectOption {sValue: index, sLabel: sMonth, bSelected:false} %}
11        {% endfor %}
12    {% EndUISelect %}
13{% EndUIForm %}

The output is:

../../_images/Hello3.png