如何在Symfony中跨视图共享对象?
我在我的实体中实现了Serializable类,这样我就可以将对象存储在会话中。但是,由于我的实体包含抽象方法,我需要在课堂上实现可序列化方法,我相信这将是我的最后手段。
在那之前,我想找到一个替代解决方案,而不是将Object存储在我的数据库中的临时表中(这与完全没有做任何事情完全相同,因为我需要在每个控制器中调用数据库显示视图)
这是我的情景:
我有两个文件:layout.html.twig
和sidebar.html.twig
我的DefaultController里面有一个名为buildSidebar()
的方法,如下所示
public function buildSidebar($userId = 0) {
$projects = $this->getDoctrine()->getRepository('SuperBundle:Projects')->findBy(array('userId' => $userId), array('cratedDate' => DESC), 10);
return $this->render(
'SuperBundle:sidebar.html.twig',
array('projects' => $projects)
);
}
然后在我的layout.html.twig
文件中,我在第77行中有以下代码块:
{% render controller("SuperBundle:Default:buildSidebar", {'userId': 37}) %}
当我测试出来时,symfony会抛出一个异常说:
function controller doesn't exist in SuperBundle::layout.html.twig in line 77
我试图以这种方式嵌入控制器:
{{ render(controller("SuperBundle:Default:buildSidebar", {'userId': 37}) }}
此方法抛出异常unexpected name of value controller
:
{{ render controller("SuperBundle:Default:buildSidebar", {'userId': 37}) }}
我也是这样尝试的,同样的结果function controller does not exist
:
{%render(“控制器”(“SuperBundle:默认:buildSidebar”,{'userId':37})%}
我错过了什么?我按照Symfony的文件写了这封信,其中没有任何东西对我有帮助。
答案 0 :(得分:3)
是的,您可以通过枝条扩展来访问服务。 http://symfony.com/doc/current/cookbook/templating/twig_extension.html
<?php
namespace You\UserBundle\Twig;
use Symfony\Component\Security\Core\SecurityContext;
class YourExtension extends \Twig_Extension
{
protected $doctrine;
function __construct($doctrine)
{
$this->doctrine = $doctrine;
}
public function getUsers()
{
$em = $this->doctrine->getManager();
$result = $em
->getRepository('yourEntity')->findAll();
return $result;
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('get_users', array($this, 'getUsers'))
);
}
public function getName()
{
return 'your_extension';
}
}
或者您可以在树枝视图中包含一个控制器,如:
{{ render(controller('YourUserBundle:YourController:youraction')) }}
来源:http://symfony.com/blog/new-in-symfony-2-2-the-new-fragment-sub-framework