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?
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
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:
In ControllerName::MethodName render test.twig file:
2. Use the KernelResponse event to dynamically add global variables
Only the core code is written, you also need to configure the service