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

时间:2014-02-06 22:24:13

标签: symfony twig

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

3 个答案:

答案 0 :(得分: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';
    }
}

然后我在我的services.yml

中注册了它
services:                
    mg_admin.bundles.extension:
        class: MG\AdminBundle\Twig\Bundles
        arguments: [@service_container]
        tags:
            - { name: twig.extension } 

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

{% if bundleExists('MGEmailBundle') %}
    {% include 'MGEmailBundle:SideBar:sidebar.html.twig' %}
{% endif %}

答案 1 :(得分:5)

$this->container->getParameter('kernel.bundles');

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

然后你应该轻松​​达到你的目标

答案 2 :(得分:-1)

如果您要检查的捆绑包是特定捆绑包,并且您知道主要的类名称,则最简单的方法可能是:

if (class_exists('Acme\CommentBundle\AcmeCommentBundle'))
{
    // Bundle exists and is loaded by AppKernel...
}