我编写了从数据库中获取模板的自定义树枝加载程序,它在树枝“独立”库中起作用。现在,我想在symfony2中使用它,但找不到通过Symfony2设置在哪里更改树枝加载程序的地方。

提前提示任何提示

有帮助吗?

解决方案

看一下 这一页 在Github。特别 <parameter key="twig.loader.class">Symfony\Bundle\TwigBundle\Loader\Loader</parameter>

您可以在config.yml中配置此键

其他提示

注册您自己的树枝加载程序 +告诉Twig_loader_chain首先尝试使用加载器加载。您可以在您的 twig_loader_chain 您想要的。

services:
    Acme.corebundle.twig.loader.filesystem:
        class: Acme\CoreBundle\Twig\Loader\Filesystem
        tags:
            - { name: templating.loader }

    Acme.corebundle.twig_chain_loader:
        class: Twig_Loader_Chain
        calls:
            - [ addLoader, [@Acme.corebundle.twig.loader.filesystem] ]
            - [ addLoader, [@twig.loader] ]

现在您应该创建加载程序。树枝加载程序必须实现 Twig_loaderInterface.

acme/corebundle/twig/loader/filesystem.php

伪代码:

namespace Acme\CoreBundle\Twig\Loader;

use Twig_LoaderInterface;


class Filesystem implements Twig_LoaderInterface {

    /**
     * {@inheritdoc}
     */
    public function getSource($name)
    {
        //code...
    }

    /**
     * {@inheritdoc}
     */
    protected function findTemplate($name)
    {
        //code...
    }

    /**
     * {@inheritdoc}
     */
    public function isFresh($template, $time)
    {
        //code...
    }

    //...
}

现在,我们已经定义了我们的服务并创建了一个新的加载程序。问题是Twig不了解我们的新Twig_loader,并且仍然使用自己的-default-“ Twig.loader”。

在CLI上检查运行:

应用程序/控制台容器:debug twig.loader

为了在自己的捆绑包外修改服务,您必须使用CompilerPasses。创建我们自己的加载程序服务为树枝环境的分配:

acme/coreBundle/dependencyIndoction/Compiler/twigfileleloaderpass.php

<?php

namespace Acme\CoreBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

class TwigFileLoaderPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('twig');
        $definition->addMethodCall('setLoader', array(new Reference('Acme.corebundle.twig_chain_loader')));
    }
}

有一个“ addMethodCall”调用,它只能像在服务定义中定义设置器注入。不同之处在于,在编译器通行证中,您可以访问每个服务,而不仅可以访问您自己的服务。如您所见,链条加载器已被定义为树枝环境的新装载机。

要完成此任务,您必须告诉Symfony,它应该使用此编译器通行证。可以在您的捆绑类中添加编译器通行证:

acme/corebundle/acmecorebundle.php

<?php

namespace Acme\CoreBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;

use Acme\CoreBundle\DependencyInjection\Compiler\TwigFileLoaderPass;

class AcmeCoreBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);
        $container->addCompilerPass(new TwigFileLoaderPass());
    }
}

如果相应的文件不存在,则您的新twig_loader_filesystem会引发错误,并且链加载程序将继续以默认的树枝加载程序作为后备。

要覆盖您的config.yml中的密钥,您需要在服务下而不是小树枝进行操作,因为目前不支持配置解析器(2.0.9)

twig:
    cache:...
    debug:...
    ...

services:
        twig.loader:
            class: Acme\CoreBundle\Twig\Loader\FilesystemLoader
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top