如何检查树枝中是否存在束?

Mik*_*eGA 4 symfony twig

我的应用程序由八个包组成,在我的主要布局中我想检查某个包是否存在所以我可以包含一个子模板,我该怎么做呢?

Mik*_*eGA 10

感谢@DonCallisto,我决定在我的模板中使用twig函数,以下是我的twig扩展.

<?php

namespace MG\AdminBundle\Twig;

use Symfony\Component\DependencyInjection\ContainerInterface;
class Bundles extends \Twig_Extension {
    protected $container;

    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction(
                'bundleExists', 
                array($this, 'bundleExists')
            ),
        );
    }


    public function bundleExists($bundle){
        return array_key_exists(
            $bundle, 
            $this->container->getParameter('kernel.bundles')
        );
    }
    public function getName() {
        return 'mg_admin_bundles';
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我在我的services.yml中注册了它

services:                
    mg_admin.bundles.extension:
        class: MG\AdminBundle\Twig\Bundles
        arguments: [@service_container]
        tags:
            - { name: twig.extension } 
Run Code Online (Sandbox Code Playgroud)

现在在我的twig模板中,我可以检查这样的注册包:

{% if bundleExists('MGEmailBundle') %}
    {% include 'MGEmailBundle:SideBar:sidebar.html.twig' %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)


Don*_*sto 5

$this->container->getParameter('kernel.bundles');
Run Code Online (Sandbox Code Playgroud)

将返回所有已注册的包(类名).您可以将该列表 - 或将其解析 - 传递到控制器并将其传递给您的树枝视图

然后你应该很容易达到你的目标