uniibu/better-php-view

将 PHP 视图脚本渲染成 PSR-7 响应对象。

dev-master 2017-04-12 22:39 UTC

This package is not auto-updated.

Last update: 2024-09-20 22:43:16 UTC


README

Build Status

Better-PHP-View

这是一个将 PHP 视图脚本渲染成 PSR-7 响应对象的渲染器。它与 Slim 框架 3 兼容良好。

当前版本

这个版本是从原始 PHP-view https://github.com/slimphp/PHP-View 分支出来的。

这个版本还增加了使用 zend-escaper (https://github.com/zendframework/zend-escaper) 进行可选转义的功能,以及使用 $PHPview->fetch('模板名称') 包含其他视图的能力。

包含的模板必须位于相同的模板目录中。

包含的模板也可以访问主模板上传递的属性。

要使用转义函数,只需在调用 $PHPview->render 时添加转义类型,例如 $PHPview->render($response,'template.php',['args' => 'value'],'html')

如果省略了转义类型,则不会进行转义。它只会转义关联数组的值。

跨站脚本(XSS)风险(本版本为可选功能)

请注意,PHP-View 没有内置的 XSS 攻击缓解功能。使用 htmlspecialchars() 或类似 zend-escaper 的组件是开发者的责任。或者,可以考虑使用 Twig-View

模板

您可以在 PHP 模板中使用 $this$this 将是实际的 PhpRenderer 对象,这将允许您渲染子模板。

安装

使用 Composer 安装

composer require uniibu/better-php-view:dev-master

在 Slim 3(本版本)中的使用方法

use Slim\Views\PhpRenderer;

include "vendor/autoload.php";

$app = new Slim\App();
$container = $app->getContainer();
$container['renderer'] = new PhpRenderer("./templates");

$app->get('/hello/{name}', function ($request, $response, $args) {
    return $this->renderer->render($response, "/hello.php", $args, 'html');
});

$app->run();

在任何 PSR-7 项目中的使用方法

//Construct the View
$phpView = new PhpRenderer("./path/to/templates");

//Render a Template
$response = $phpView->render(new Response(), "/path/to/template.php", $yourData, 'html');

转义选项(本版本)请参考 https://github.com/zendframework/zend-escaper

'html' = zend->escapeHtml

'attr' = zend->escapeHtmlAttr

'url' = zend->escapeUrl

'js' = zend->escapeJs

'css' = zend->escapeCss

模板变量(本版本)

您现在可以向渲染器添加变量和转义类型,这些变量将可供您渲染的所有模板使用。

// via the constructor
$templateVariables = [
    "title" => "Title"
];
$phpView = new PhpRenderer("./path/to/templates", $templateVariables, 'html');

// or setter
$phpView->setAttributes($templateVariables);

// or individually
$phpView->addAttribute($key, $value);

通过 ->render() 传递的数据优先于属性。

$templateVariables = [
    "title" => "Title"
];
$phpView = new PhpRenderer("./path/to/templates", $templateVariables, 'js');

//...

$phpView->render($response, $template, [
    "title" => "My Title"
], 'attr');
// In the view above, the $title will be "My Title" and not "Title"

异常

\RuntimeException - 如果模板不存在

\InvalidArgumentException - 如果 $data 包含 'template'