maba/twig-template-modification-bundle

用于批量修改 Twig 模板的工具包

1.0.1 2016-06-11 18:37 UTC

This package is auto-updated.

Last update: 2024-09-10 20:58:33 UTC


README

此工具包的功能是什么?

此工具包本身不执行任何操作 - 它帮助您通过用其他 Twig 代码替换解析节点来修改现有的 twig 模板。

它可以用来一次性编辑多个模板。

使用示例请参阅 maba/webpack-migration-bundle.

安装

composer require maba/twig-template-modification-bundle

AppKernel 内部

new Maba\Bundle\WebpackBundle\MabaTwigTemplateModificationBundle(),

使用方法

创建一个实现 TwigNodeReplacerInterface 的服务。

use Maba\Bundle\TwigTemplateModificationBundle\Service\TwigNodeReplacerInterface;
use Maba\Bundle\TwigTemplateModificationBundle\Entity\TemplateContext;
use Twig_Node as Node;

class MyNodeReplacer implements TwigNodeReplacerInterface
{
        /**
         * @param Node $node
         * @param TemplateContext $context
         *
         * @return null|string string if this node should be replaced with given twig code
         */
        public function replace(Node $node, TemplateContext $context)
        {
            if ($node instanceof NameExpression && $node->getAttribute('name') === 'my_var') {
                return '123';
            }
            return null;
        }
}

replace 方法将在每个 twig 模板中的每个节点上被调用。

如果返回字符串(不是 null),则节点将被给定字符串内容替换。

TemplateContext 包含模板名称。您还可以向其中添加通知(例如,无法替换某些节点)并保存属性(稍后可以重用它们 - 相同的上下文用于同一模板中的每个节点)。

使用以下代码启动模板重写

$factory = $container->get('maba_twig_template_modification.factory.files_replacer');
$replacer = $factory->createFilesReplacer(new MyNodeReplacer());

// both arguments (closures) are optional
$replacer->replace(function($filePath, $contents, $notices) {
    // log or write to output before replacing file in $filePath with $contents
}, function (array $notices) use ($output) {
    // log or write to output notices
});

您也可以使用工厂服务通过依赖注入创建替换器

<service id="acme.files_replacer"
         class="Maba\Bundle\TwigTemplateModificationBundle\Service\FilesReplacer">
     <factory service="maba_twig_template_modification.factory.files_replacer" method="createFilesReplacer"/>
    <argument type="collection">
        <argument type="service" id="acme.my_node_replacer"/>
    </argument>
</service>

重要! 代码将替换您工具包和应用程序目录中的模板内容 - 确保只在未提交任何更改的版本控制系统下运行。

运行测试

Travis status

composer install
vendor/bin/phpunit