Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for the existence of a bundle in twig?

Tags:

twig

symfony

My application is made up with eight bundles, within my main layout I would like to check if a certain bundle exists so I can include a sub template, how do I go about doing this?

like image 334
MikeGA Avatar asked Dec 08 '22 09:12

MikeGA


1 Answers

Thanks to @DonCallisto, I decided to make a twig function to use in my templates, the following is my twig extension.

<?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';
    }
}

I then registered it in my services.yml

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

Now in my twig templates I can check for registered bundles like this:

{% if bundleExists('MGEmailBundle') %}
    {% include 'MGEmailBundle:SideBar:sidebar.html.twig' %}
{% endif %}
like image 77
MikeGA Avatar answered Dec 11 '22 09:12

MikeGA