我有同样的需求,所以我创建了自己的扩展:
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 %}