首页 > Symfony2 layout.html.twig中需要查询数据显示怎么操作?

Symfony2 layout.html.twig中需要查询数据显示怎么操作?

layout.html.twig中如果有公共部分比如侧边栏 需要查询数据操作显示出来,怎么操作比较好啊?


http://symfony.cn/docs/quick_tour/the...


两种方法:

一、把 layout 中需要从数据库中读取数据的地方单独分离一个 .twig 文件(比如 test.twig),在 layout 中使用 render Controller 方法:

{{ render(controller('AppBundle:ControllerName:MethodName', { 'params': 3 })) }}

在 ControllerName::MethodName 里 render test.twig 文件:

public function MethodName($params)
{
    $repository = $this->get('doctrine.orm.entity_manager')
        ->getRepository('AppBundle:EntityName');
    
    return $this->render('AppBundle:ControllerName:test.twig', array(
        'result' => $repository->findByParams($params)
    ));
}

二、利用 KernelResponse 事件动态添加全局变量


public function __construct(ContainerInterface $container)
{
    // container 需要通过 service.yml 注入
    $this->container = $container;
}

public function onKernelResponse()
{
    $twig = $this->container->get('twig');
    $em   = $this->container->get('doctrine.orm.entity_manager');
    
    $repository = $em->getRepository('AppBundle:EntityName');

    $twig->addGlobal('result', $repository->findByParams());
}

只写了核心代码,你还需要配置 service

【热门文章】
【热门文章】