search

Home  >  Q&A  >  body text

How to query and display data in Symfony2 layout.html.twig?

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梦2792 days ago658

reply all(2)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-16 16:48:16

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

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-16 16:48:16

    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

    reply
    0
  • Cancelreply