简体   繁体   English

在twig模板中将对象渲染为上下文

[英]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. render()函数不接受对象。

Is there any way to render the object directly?. 有没有办法直接渲染对象?

And I do not mean an "objectToArray" solution. 我并不是指“objectToArray”解决方案。

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. 方法render的第二个参数采用数组传输数据到视图,因此您只需将对象作为具有指定键的数组的值。 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 希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM