dhii/php-template

具体的PHP(PHTML)模板实现。

v0.1.0-alpha1 2021-10-20 09:52 UTC

This package is auto-updated.

Last update: 2024-09-20 16:24:41 UTC


README

Build Status Code Climate Test Coverage Latest Stable Version

具体的PHP(PHTML)模板实现。

详细信息

这是Dhii输出渲染标准的实现,具体来说是模板。它允许使用抽象接口消费基于文件的PHP模板。现在可以将渲染外包给标准化的、无状态的PHP模板文件,就像使用任何其他模板一样,无需知道内容来源。

由于这个实现基于PHP文件,因此决定将模板渲染的关注点与评估PHP文件的关注点分开,因为后者本身就有用,并且可以使模板实现更简洁。

使用方法

以下示例解释了如何配置模板工厂,以及如何使用它生成符合标准的模板。然后使用上下文渲染该模板。请注意以下内容

  1. 路径为template.php的文件用于生成输出。
  2. 上下文成员通过$c('key')检索。
  3. 可以使用uc函数与$f('uc')一起使用。
  4. 默认上下文成员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>