ldf / gutenberg
基于 PHP 的模板
Requires
- php: >=7.1
Requires (Dev)
- fzaninotto/faker: ~1.7
- mockery/mockery: ~1.1.
- phpmetrics/phpmetrics: dev-master
- phpunit/phpunit: ~7
This package is auto-updated.
Last update: 2024-09-28 21:50:44 UTC
README
Gutenberg 是一个用 PHP 编写的视图渲染器,基于视图 必须 完全与逻辑分离的事实。
该系统将允许您轻松地替换一些变量为值,并以简单的方式为 CMS 组合视图,但您不会找到控制结构,如 if/else 语句或模板继承。如果您正在寻找这类功能,我建议您查看 Blade 或 Twig。
如何安装
您可以使用 composer 安装 Gutenberg
composer require ldf/gutenberg
实例化 Gutenberg
Gutenberg 通过名为 Gutenberg
的构建器类进行实例化
$Gutenberg = Gutenberg::ForWorkspace('./path/to/templates');
通过使用流畅的 API,您将能够设置一些额外的行为。以下行将构建一个启用了 Wipe Out 模式的 Gutenberg 对象
// Get the object $Gutenberg = Gutenberg::ForWorkspace('./path/to/templates') ->withWipeOut(); // Call the render function to get the rendered page return $Gutenberg->render('page', [ 'var1' => 'value1', 'var2' => 'value2', ]);
模板文件
模板文件只是 .html 文件(因为它们预期只包含 html 和一些 Guttemberg 调整)。它们必须放置在工作区中。
工作区基本上是目录的路径。
模板通过 ID 引用,按照惯例,解析为工作区中的文件。
例如,由 myTemplate
标识的模板将解析为路径 ./workspace/myTemplate.html
,另一个由 partials/_widget
标识的模板将解析为路径 ./workspace/partials/_widget.html
- 顺便说一句,建议您按照惯例,在您的部分文件前缀中包含下划线
_
(您可能已经熟悉了这个约定)。
如果您决定为模板使用除 .html
之外的扩展名,您可以使用类似 myTemplate.tpl
的方式将其指定为标识符的一部分。
关键词
Gutenberg 提供了一些表达式,允许您在模板中定义一些动态点。
一般来说
Gutenberg 中的表达式是您放置在双大括号之间的一切。
如果您想打印双大括号,必须使用 html 实体
The value of variable "myvar" is {{ myvar }} {{This will be displayed in the html.|;|
变量
变量将表示为 {{ varname }}
导入
{{ import _partialTemplateId }}
请注意,在这种情况下,ID 以下划线 _
开头。这样,Gutenberg 就知道这个模板是一个部分模板。按照惯例,部分模板必须以下划线开头。实际上,如果它们不以下划线开头,导入表达式将被忽略。
请注意,您已经在一个工作区中,因此您不能从另一个工作区导入模板。这样,您被迫避免跨依赖。
包装器
{{ wrapper tplname}}
我们不支持继承——不,我们不喜欢继承。相反,您可以将模板包装。想象一下包装就像是一种反向导入,其中被包装的模板可以定义一个——仅此一个——要包装的模板。
当您使用包装时,源代码文件必须正好以包装命令开始。
包装器使用 {{ content }}
标记来定义内部模板将被包装的位置。
注释
{{-
(即 X-Wing 运算符)
该行的其余部分是注释,将被忽略。对于多行注释,您可以发送一些 X-Wing 空间船。
{{-
{{- This is a multi-line comment.
{{- You can use it as header of template files.
{{- Everything you write in a comment will be ignored and will not appear in the ouput.
{{-
<strong>
This will be rendered
</strong>
现在,做个好孩子,去给你的代码添加一些注释。
控制结构
那么,我该如何添加一些结构,例如 if
/else
或 foreach
呢?答案是简单:不能。
逻辑不应该出现在你的模板中,所以你必须确保传递一些现成的替换值。
额外选项
通过使用构建器,您将能够配置一些额外选项。
清除
您可以通过调用 withWipeOut
启用清除功能。
当启用清除选项时,任何未识别的 Gutenberg 标签,例如 {{ unknownVariable }},将被从模板中清除。将引发 E_USER_WARNING 级别的错误。
$Gutenberg = Gutenberg::ForWorkspace('./path/to/templates') ->withWipeOut() ->get();
扩展 Gutenberg 的功能。
Gutenberg 提供了一个添加自定义编译器的功能。这将允许您创建自己的语言表达式。您可以通过实现 ICompiler 来添加自己的语言表达式调用。
class MyCustomCompiler implements \Ldf\Gutenberg\ICompiler { public function compile(string $tpl) : string { ... } }
您可以添加任意多的自定义编译器。
Gutenberg::ForWorkspace('./FakeTemplates') ->addCustomCompiler($myCustomCompiler1) ->addCustomCompiler($myCustomCompiler2)
只需注意编译器是按顺序执行的,从核心编译器开始,然后是核心选项。自定义编译器将在最后执行。