6

In my Symfony2 bundle, I need to check if a function (an extension) is defined. More specifically, if the KnpMenuBundle is installed I use that one in my bundle, otherwise I will render the plugin myself.

I tried this, but this of course doesn't work:

{% if knp_menu_render() is defined %}
    {# do something #}
{% else %}
    {# do something else #}
{% endif %}

Is there a test/function/filter to check if a function is defined? If not, is there another way to check if the KnpMenuBundle is installed in the application?

Wouter J
  • 41,455
  • 15
  • 107
  • 112

2 Answers2

3

Write a function in a Twig Extension which would check if bundle is enabled.

List of registered bundles is stored in the kernel.bundles parameter.

Twig extensions are registered as services. This means you can pass any other service or a parameter to your extension:

<services>
    <service id="acme.twig.acme_extension" class="Acme\DemoBundle\Twig\AcmeExtension">

        <argument>%kernel.bundles%</argument>

        <tag name="twig.extension" />
    </service>
</services>

In your Twig function or filter you can later use a service or a parameter which you've passed to an extension.

Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125
  • Thank you, I had thought of that, but I thought is was not a good practise to create an extension for this in a bundle which isn't related to the function of the extension? (for instance, a `TwigBundle` is more related) – Wouter J Dec 22 '12 at 22:21
1

I had the same need, so I created my own extension:

class IsLoadedExtension extends \Twig_Extension
{
    /**
     * @var \Twig_Environment
     */
    protected $environment;

    public function initRuntime(\Twig_Environment $environment)
    {
        $this->environment = $environment;
    }

    /**
     * Returns a list of functions to add to the existing list.
     *
     * @return array An array of functions
     */
    public function getTests()
    {
        return array(
                new \Twig_SimpleTest('loaded', [$this, 'hasExtension']),
        );
    }

    /**
     * @param string $name
     * @return boolean
     */
    function hasExtension($name)
    {
        return $this->environment->hasExtension($name);
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'amce_extension_exists';
    }
}

Then registered it in Twig:

services:
    acme_somebundle.twig.is_loaded_extension:
        class: Acme\SomeBundle\Twig\IsLoadedExtension
        tags: [{ name: twig.extension }]

And used it in twig template like this:

{% if 'knp_menu' is loaded %}
  {# use knp menu #}
{% endif %}
Tomasz
  • 11
  • 2