How to check for a beam in a twig?

My application is composed with eight packages, in my main layout I would like to check if a specific package exists, so I can include an additional template, how can I do this?

+4
source share
3 answers

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

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

Then I registered it in my .yml services

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

Now in my templates branch I can check registered packages as follows:

{% if bundleExists('MGEmailBundle') %}
    {% include 'MGEmailBundle:SideBar:sidebar.html.twig' %}
{% endif %}
+10
source
$this->container->getParameter('kernel.bundles');

( ). - direclty - twig

+5

If the package you want to check is a specific package, and you know the name of the main class, the simplest way might be:

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

Source: https://habr.com/ru/post/1525701/


All Articles