How to query and display data in Symfony2 layout.html.twig?
过去多啦不再A梦
过去多啦不再A梦 2017-05-16 16:46:16
0
2
642

layout.html.twig If there are public parts such as sidebars that need to be queried and displayed, what is the best way to operate them?

过去多啦不再A梦
过去多啦不再A梦

reply all(2)
phpcn_u1582

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

世界只因有你

Two methods:

1. Separate a .twig file (such as test.twig) in the layout where data needs to be read from the database, and use the render Controller method in the layout:

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

In ControllerName::MethodName render test.twig file:

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)
    ));
}

2. Use the KernelResponse event to dynamically add global variables


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());
}

Only the core code is written, you also need to configure the service

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template