dhii / php-template
具体的PHP(PHTML)模板实现。
v0.1.0-alpha1
2021-10-20 09:52 UTC
Requires
- php: ^7.0
- dhii/output-renderer-interface: ^0.4
Requires (Dev)
- dhii/stringable-interface: ^0.1
- mikey179/vfsstream: ^1.6
- phpunit/phpunit: ^6.0 || ^7.0
- psr/container: ^1.0
This package is auto-updated.
Last update: 2024-09-20 16:24:41 UTC
README
具体的PHP(PHTML)模板实现。
详细信息
这是Dhii输出渲染标准的实现,具体来说是模板。它允许使用抽象接口消费基于文件的PHP模板。现在可以将渲染外包给标准化的、无状态的PHP模板文件,就像使用任何其他模板一样,无需知道内容来源。
由于这个实现基于PHP文件,因此决定将模板渲染的关注点与评估PHP文件的关注点分开,因为后者本身就有用,并且可以使模板实现更简洁。
使用方法
以下示例解释了如何配置模板工厂,以及如何使用它生成符合标准的模板。然后使用上下文渲染该模板。请注意以下内容
- 路径为
template.php
的文件用于生成输出。 - 上下文成员通过
$c('key')
检索。 - 可以使用
uc
函数与$f('uc')
一起使用。 - 默认上下文成员
time
存在于模板中,尽管在渲染时并未显式提供。
配置,通常在服务定义中
use Dhii\Output\PhpEvaluator\FilePhpEvaluatorFactory; use Dhii\Output\Template\PhpTemplate\FilePathTemplateFactory; use Dhii\Output\Template\PathTemplateFactoryInterface; function (): PathTemplateFactoryInterface { return new FilePathTemplateFactory( new FilePhpEvaluatorFactory(), [ // This will be available by default in all contexts of all templates made by this factory 'time' => time(), // Let's assume it's 1586364371 ], [ // This will be available by default in all templates made by this factory 'uc' => function (string $string) { return strtoupper($string); }, ] ); };
消费,通常在控制器级别代码中
use Dhii\Output\Template\PathTemplateFactoryInterface; use Dhii\Output\Template\PhpTemplate\FilePathTemplateFactory; /* @var $fileTemplateFactory FilePathTemplateFactory */ (function (PathTemplateFactoryInterface $factory) { $template = $factory->fromPath('template.php'); echo $template->render([ 'username' => 'jcdenton', 'password' => 'bionicman', 'status' => 'defected', ]); })($fileTemplateFactory); // This is the factory created by above configuration
template.php
/* @var $c callable */ /* @var $f callable */ ?> <span class="current-time"><?= $c('time') ?><span /> <span class="username"><?= $c('username') ?></span><br /> <span class="password"><?= $c('password') ?></span><br /> <span class="status"><?= $f('uc', $c('status')) ?></span>
生成的输出
<span class="current-time">1586364371<span /> <span class="username">jcdenton</span><br /> <span class="password">bionicman</span><br /> <span class="status">DEFECTED</span>