Алексей Asked:2020-04-15 18:54:38 +0000 UTC2020-04-15 18:54:38 +0000 UTC 2020-04-15 18:54:38 +0000 UTC 枝条。来自控制器的对象 772 有一个其他人将从中继承的基本树枝模板。在此模板中(因此在每个页面上)必须显示从控制器接收到的对象的值。 在 twig 中,您可以从控制器的{{render(controller(...))}}方法中获取值,但这只能在页面上呈现。 我需要以某种方式获取对象,以便稍后循环遍历它。怎样才能做得更好? symfony 1 个回答 Voted Best Answer Алексей 2020-04-30T02:20:54Z2020-04-30T02:20:54Z 我在stackoverflow上找到了一个答案,有3种方法可以做到: 渲染生成的现成 html 代码的控制器,其中所有数据都已经迭代过,然后 {{render(controller(...)))}} 服务 树枝小部件。 我决定停止第三种方法: Widget - 带有类别和子类别的菜单 Widget 类: // src\AppBundle\Twig\MenuCategoryWidgetExtension.php namespace AppBundle\Twig; use Symfony\Component\DependencyInjection\ContainerInterface; /** * MenuCategoryWidgetExtension */ class MenuCategoryWidgetExtension extends \Twig_Extension { protected $container; function __construct(ContainerInterface $container) { $this->container = $container; } public function getFunctions() { return array ( new \Twig_SimpleFunction ( 'categories', array($this, 'getMenuCategory') ) ); } public function getMenuCategory() { $em = $this->container->get('doctrine')->getManager (); $category = $em->getRepository('AppBundle:Category')->getCategoryList(); return $category; } public function getName() { return 'WidgetExtension'; } } 设置标记为“twig.extension”的服务 // src\AppBundle\Resources\config\services.yml services: app.twig.menu_category_widget_extension: class: AppBundle\Twig\MenuCategoryWidgetExtension arguments: ["@service_container"] tags: - { name: twig.extension } 在 Twig 模板中: {% set categories = categories() %} {% for key, category in categories %} .... 此外,可以将数据插入到 html 标签中 另外,由于这个小部件会在每个页面上使用,为了不每次都对数据库进行相同的查询,我设置了缓存 // app\config\config.yml ..... orm: query_cache_driver: apc metadata_cache_driver: apc result_cache_driver: apc // src\AppBundle\Repository\CategoryRepository.php ..... $query = $qb->getQuery() ->useQueryCache(true) ->useResultCache(true, 1200, 'category_cache') 其中 1200 是以秒为单位的缓存时间。
我在stackoverflow上找到了一个答案,有3种方法可以做到:
我决定停止第三种方法: Widget - 带有类别和子类别的菜单 Widget 类:
设置标记为“twig.extension”的服务
在 Twig 模板中:
此外,可以将数据插入到 html 标签中
另外,由于这个小部件会在每个页面上使用,为了不每次都对数据库进行相同的查询,我设置了缓存
其中 1200 是以秒为单位的缓存时间。