Symfony 如何检查树枝中是否存在捆绑?
我的应用程序由八个捆绑包组成,在我的主布局中,我想检查是否存在某个捆绑包,以便我可以包含一个子模板,我该如何做Symfony 如何检查树枝中是否存在捆绑?,symfony,twig,Symfony,Twig,我的应用程序由八个捆绑包组成,在我的主布局中,我想检查是否存在某个捆绑包,以便我可以包含一个子模板,我该如何做 $this->container->getParameter('kernel.bundles'); 将返回所有已注册的捆绑包(类名)。您可以将该列表传递(或直接解析)到控制器中,并将其传递到您的细枝视图 然后你应该很容易达到你的目标多亏了@DonCallisto,我决定在我的模板中使用一个细枝函数,下面是我的细枝扩展 <?php namespace MG\Admi
$this->container->getParameter('kernel.bundles');
将返回所有已注册的捆绑包(类名)。您可以将该列表传递(或直接解析)到控制器中,并将其传递到您的细枝视图
然后你应该很容易达到你的目标多亏了@DonCallisto,我决定在我的模板中使用一个细枝函数,下面是我的细枝扩展
<?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';
}
}
现在,在我的小树枝模板中,我可以检查注册的捆绑包,如下所示:
{% if bundleExists('MGEmailBundle') %}
{% include 'MGEmailBundle:SideBar:sidebar.html.twig' %}
{% endif %}
如果要检查的bundle是一个特定的bundle,并且您知道主类名,那么最简单的方法可能是:
if (class_exists('Acme\CommentBundle\AcmeCommentBundle'))
{
// Bundle exists and is loaded by AppKernel...
}
是的,好主意。我已经想到了,但是我正在“跑开”键盘,所以我没有写一个“更复杂”的答案。这是正确的方法+1:)您不必注入整个容器,只需注入参数
%kernel.bundles%
if (class_exists('Acme\CommentBundle\AcmeCommentBundle'))
{
// Bundle exists and is loaded by AppKernel...
}