【问题标题】:Active Bundles of Symfony2Symfony2 的活动捆绑包
【发布时间】:2015-05-20 14:41:15
【问题描述】:

我正在尝试显示我的 Bundles 的菜单,但我只需要显示活动的 Bundles,我如何才能在 Twig 中获取活动的 Bundles?

感谢和问候!

【问题讨论】:

    标签: symfony twig bundles


    【解决方案1】:

    bundle 列表存储在内核中。

    你必须创建一个 twig 扩展 BundleExtension 并将内核作为依赖项传递:

    <?php 
    
    namespace MyBundle\Twig\Extension;
    
    use Symfony\Component\HttpKernel\KernelInterface;
    
    class BundleExtension extends \Twig_Extension 
    {
    
        protected $kernel;
    
        public function __construct(KernelInterface $kernel)
        {
            $this->kernel = $kernel;
        }
    
        /**
         * {@inheritdoc}
         * @see Twig_Extension::getFunctions()
         */
        public function getFunctions()
        {
            return array(
                'getBundles' => new \Twig_SimpleFunction('getBundles', array($this, 'getBundles')),
            );
        }
    
         public function getBundles()
         {
            return $this->kernel->getBundles();
         }
    
        /**
         * {@inheritdoc}
         * @see Twig_ExtensionInterface::getName()
         */
        public function getName()
        {
            return 'get_bundles';
        }
    }
    

    将其注册为服务:

    services:
        bundle_extension:
            class: MyBundle\Twig\Extension\BundleExtension
            arguments: ['@kernel']
            tags:
               - { name: twig.extension }     
    

    现在在你的树枝模板中:

    {% set bundles = getBundles() %}
    {% for bundle in bundles %}
        {{ bundle.getName()}}<br/>
    {% endfor %}
    

    【讨论】:

    • 仅供参考:{{ bundle.name }} 的作用与 {{ bundle.getName() }} 相同。
    猜你喜欢
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多