【问题标题】:Check if function/extension is defined检查是否定义了功能/扩展
【发布时间】:2012-12-22 15:42:03
【问题描述】:

在我的 Symfony2 包中,我需要检查是否定义了函数(扩展)。更具体地说,如果安装了 KnpMenuBundle,我会在我的包中使用它,否则我将自己渲染插件。

我试过了,但这当然行不通:

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

是否有测试/函数/过滤器来检查函数是否已定义?如果没有,是否有其他方法可以检查 KnpMenuBundle 是否安装在应用程序中?

【问题讨论】:

    标签: symfony twig knpmenubundle


    【解决方案1】:

    Twig Extension 中编写一个函数来检查捆绑包是否启用。

    已注册捆绑包的列表存储在kernel.bundles 参数中。

    Twig 扩展被注册为服务。这意味着您可以将任何其他服务或参数传递给您的扩展:

    <services>
        <service id="acme.twig.acme_extension" class="Acme\DemoBundle\Twig\AcmeExtension">
    
            <argument>%kernel.bundles%</argument>
    
            <tag name="twig.extension" />
        </service>
    </services>
    

    在您的 Twig 函数或过滤器中,您稍后可以使用已传递给扩展的服务或参数。

    【讨论】:

    • 谢谢,我曾想过,但我认为在与扩展功能无关的捆绑包中为此创建扩展不是一个好习惯? (例如,TwigBundle 更相关)
    【解决方案2】:

    我也有同样的需求,所以我创建了自己的扩展:

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

    然后在Twig中注册:

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

    并像这样在树枝模板中使用它:

    {% if 'knp_menu' is loaded %}
      {# use knp menu #}
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 2014-11-02
      相关资源
      最近更新 更多