deniaz / terrific-twig
扩展以在 Twig 中采用 Terrific 前端方法论。目前它向 Twig 添加了一个自定义组件标签,模仿 Nitro 的 handlebars 辅助器。
Requires
- php: >=5.4
- twig/twig: ~1.24
This package is not auto-updated.
Last update: 2019-02-20 18:27:25 UTC
README
目前它向 Twig 添加了一个自定义 component
标签,模仿 Nitro 的 handlebars 辅助器。
安装
使用 composer
$ composer require namics/terrific-twig
需求
当前支持以下版本的 PHP。
PHP 5.4(已弃用。构建失败,因为测试依赖于::class
.)- PHP 5.5
- PHP 5.6
- PHP 7
- HHVM
设置
步骤 1:实现 TemplateInformationProvider
class TemplateInformationProvider implements TemplateInformationProviderInterface { public function getPaths() { return []; // List of path where Terrific Components can be found, e.g. (/var/www/example.com/frontend/components) } public function getFileExtension() { $fileExtension = 'html.twig'; return $fileExtension; } }
步骤 2:实现 ContextProviderInterface
class ContextProvider implements ContextProviderInterface { public function compile(Twig_Compiler $compiler, Twig_Node $component, Twig_Node $dataVariant, $only) { // ... } }
步骤 3:添加 TerrificLoader
$loader = ...; $chain = new Twig_Loader_Chain([$loader, new TerrificLoader(new TemplateInformationProvider)]); $twig = new Twig_Environment($chain);
步骤 4:添加 TerrificExtension
$twig = new Twig_Environment($chain); $twig->addExtension(new TerrificExtension(new ContextProvider));
步骤 5:大功告成!
使用
{# Includes the component, component's default data is merged with the context #} {% component 'Example' %} {# Includes the component, the default data is injected as a child context #} {% component 'Example' only %} {# Includes the component, but a variantion of the component data is merged with the context #} {% component 'Example' 'example-variant' %} {# Includes the component, but a variantion of the component data is injected as a child context #} {% component 'Example' 'example-variant' only %} {# Includes the component, data object is merged with the context #} {% component 'Example' { title: 'Inject an Object' } %} {# Includes the component, data object is injected as a child context #} {% component 'Example' { title: 'Inject an Object' } only %}
文档
扩展
此扩展为 Twig 提供了出色的扩展。目前该扩展提供 ComponentTokenParser
。
令牌解析器
令牌解析器包含组件标签的解析步骤。它将流标记为不同的节点(component
、data
)和一个属性(only
)。
此功能基于出色的 Twig_TokenParser_Include
。
节点
节点将标记化的标签编译成 PHP。要查看一些输出,请检查 ComponentTest
。
加载器
TerrificLoader
扩展了 Twig_Loader_Filesystem
,因为它实际上是从文件系统中加载模板的。一个实现 TemplateLocatorInterface
的实例提供了加载器应搜索模板的路径。
模板信息提供者
TemplateInformationProviderInterface
的一个实现应返回模板所在的路径列表。这些路径应采用以下形式:`['frontend/components/atoms', 'frontend/components/molecules', 'frontend/components/organisms']`。组件目录将由 TerrificLoader
提供(`Example/example.[ext]`)。
上下文提供者
这是最棘手的部分。实现了ContextProviderInterface
的实例决定了哪些数据将提供给Twig模板。待办事项:关于这一点将详细介绍。
配置读取器
读取nitro的config.json
并解析组件路径和文件扩展名等关键信息。
鸣谢
本项目部分由Namics赞助。