Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render object as context in twig template

How to render an object instead of array, like we usually do?

echo $twig->render('index.html', array('name' => 'Fabien'));

The render() function does not accept an object.

Is there any way to render the object directly?.

And I do not mean an "objectToArray" solution.

like image 580
user3537765 Avatar asked Aug 31 '25 22:08

user3537765


1 Answers

The second parameter of the method render take an array for transport data to the view, so you simply put your object as value of the array with a specified key. Something like this:

$object = new People()
$object->setName('Fabien');
echo $twig->render('index.html', array('obj' => $object));

And use in the template as

{{ obj.name }}

Hope this help

like image 82
Matteo Avatar answered Sep 03 '25 14:09

Matteo