kokspflanze/zfc-twig

Laminas/Zend Framework 模块,提供 Twig 渲染策略和扩展,以便从模板中渲染操作或触发事件

4.1.1 2022-12-01 22:22 UTC

README

ZfcTwig 是一个模块,它将 Twig 模板引擎与 Laminas / Zend Framework 集成。

信息

这是 ZF-Commons/ZfcTwig 的分支。我添加了对 ZF3 的支持,因此该模块与 Laminas / Zend Framework 2 和 3 兼容。如果您发现了一个错误,请报告,只需在 gitter 上给我发私信或打开一个 PullRequest。

安装

  1. "kokspflanze/zfc-twig": "dev-master" 添加到您的 composer.json 文件,并运行 php composer.phar update
  2. ZfcTwig 添加到您的 config/application.config.php 文件中的 modules 键下。

配置

ZfcTwig 默认提供合理的配置,但通过 zfctwig 配置键提供可选配置。有关所有可用选项的详细信息,请参阅 模块配置文件 类。

文档

设置 Twig 扩展

可以通过将 FQCN 添加到 extensions 配置键中来在 Twig 中注册扩展,这正是 ZfcTwig 扩展注册的方式。

// in module configuration or autoload override
return [
    'zfctwig' => [
        'extensions' => [
            // an extension that uses no key
            'My\Custom\Extension',

            // an extension with a key so that you can remove it from another module
            'my_custom_extension' => 'My\Custom\Extension'
        ]
    ]
];

配置 Twig 加载器

默认情况下,ZfcTwig 使用 Twig\Loader\ChainLoader,以便可以将加载器链接在一起。使用一个方便的默认配置使用一个 文件系统加载器,路径设置为 module/Application/view,这对于大多数实例都应该是开箱即用的。如果您希望将额外的加载器添加到链中,您可以通过将服务管理器别名添加到 loaders 配置键来注册它们。

// in module configuration or autoload override
return [
    'zfctwig' => [
        'loader_chain' => [
            'MyTwigFilesystemLoader'
        ]
    ]
];

// in some module
public function getServiceConfiguration()
{
    return [
        'factories' => [
            'MyTwigFilesystemLoader' => function($sm) {
                return new \Twig\Loader\FilesystemLoader('my/custom/twig/path');
            }
        ]
    ];
}

使用 ZF 视图助手

通过 ZfcTwig\Twig\FallbackFunction 函数支持使用 ZF 视图助手。

{# Simple view helper echo #}
{{ doctype() }}

{# Echo with additional methods #}
{{ headTitle('My Company').setSeparator('-') }}

{# Using a view helper without an echo #}
{% do headTitle().setSeparator('-') %}

{# Combining view helpers #}
{% set url = ( url('my/custom/route') ) %}

示例

骨架应用程序的 .twig 文件示例可以在 examples 文件夹中找到。

注意事项

ZF 不太支持具有视图助手的多个渲染器。作为解决方案,ZfcTwig 注册了自己的 HelperPluginManager,该管理器扩展了默认的 Laminas\View\HelperPluginManager 并添加了默认管理器作为对等管理器。这允许 ZfcTwig 为需要它的视图助手注册自己的渲染器,并回退到默认管理器以处理不需要渲染器的视图助手。

作为注意事项,您必须使用 ZfcTwig 注册需要渲染器的视图助手。在 config/module.config.php 中的示例中,默认导航助手的 HelperConfig 已使用 ZfcTwig 注册。