I am trying to pass more than one array to the Twig display() method. My code contains several functions returning arrays. I do have one parent template (parent.phtml) and several child templates (child_n.phtml) which are extending the parent template.
This is the relevant part of index.php:
$template = $twig->loadTemplate('child_1.phtml');
$template->display(function_1());
Declaration of the Twig environment etc. is happening in another file which is included.
With the code above everything works fine. But what I want to do, is displaying more than one array. So I have tried
$template->display(function_1(), function_2());
This does not work. When using $template->display();
twice, the parent template is being displayed twice...
So what might be a solution?
You have several ways to solve your problem :
1) If your function_1()
and function_2()
do return arrays with distinct keys, you can use array_merge to merge all arrays.
$template->display(array_merge(function_1(), function_2()));
So if function_1()
returns array("a" => 42)
and function_2()
returns array("b" => 84)
, you can use {{ a }}
and {{ b }}
in your twig file to access your values.
2) If your function_1()
and function_2()
do return arrays with some similar keys, you need to give a name to them :
$twigVars = array();
$twigVars['array1'] = function_1();
$twigVars['array2'] = function_2();
$template->display($twigVars);
So if function_1()
returns array("a" => 42)
and function_2()
returns array("a" => 84)
, you can use {{ array1.a }}
to access 42 and {{ array2.a }}
to access 84 in your twig file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.