geggleto / slim-renderer
3.1.0
2021-02-03 14:28 UTC
Requires
- php: ^7.3 || ^8.0
- psr/http-message: ^1.0
Requires (Dev)
- phpunit/phpunit: ^8.0
- slim/psr7: ^1
- squizlabs/php_codesniffer: ^3.5
README
PHP 渲染器
这是一个将 PHP 视图脚本渲染为 PSR-7 响应对象的渲染器。它与 Slim 框架 4 配合良好。
跨站脚本(XSS)风险
请注意,PHP-View 没有内置的 XSS 攻击缓解措施。使用 htmlspecialchars()
或类似 laminas-escaper 的组件是开发者的责任。或者,考虑使用 Twig-View。
安装
使用 Composer 安装
composer require slim/php-view
与 Slim 4 一起使用
use Slim\Views\PhpRenderer; include "vendor/autoload.php"; $app = Slim\AppFactory::create(); $app->get('/hello/{name}', function ($request, $response, $args) { $renderer = new PhpRenderer('path/to/templates'); return $renderer->render($response, "hello.php", $args); }); $app->run();
请注意,您可以将 PhpRenderer 实例化放置在您的 DI 容器中。
与任何 PSR-7 项目一起使用
//Construct the View $phpView = new PhpRenderer("path/to/templates"); //Render a Template $response = $phpView->render(new Response(), "hello.php", $yourData);
模板变量
您现在可以向渲染器添加变量,这些变量将可供所有渲染的模板使用。
// via the constructor $templateVariables = [ "title" => "Title" ]; $phpView = new PhpRenderer("path/to/templates", $templateVariables); // or setter $phpView->setAttributes($templateVariables); // or individually $phpView->addAttribute($key, $value);
通过 ->render()
传递的数据优先于属性。
$templateVariables = [ "title" => "Title" ]; $phpView = new PhpRenderer("path/to/templates", $templateVariables); //... $phpView->render($response, $template, [ "title" => "My Title" ]); // In the view above, the $title will be "My Title" and not "Title"
子模板
在您的模板中,您可以使用 $this
来引用 PhpRenderer 对象以渲染子模板。如果使用布局,可以使用 fetch()
方法代替 render()
来避免将布局应用于子模板。
<?=$this->fetch('./path/to/partial.phtml', ["name" => "John"])?>
在布局中渲染
您现在可以在另一个称为布局的视图中渲染视图,这允许您构建模块化视图模板,并帮助保持视图的 DRY。
创建您的布局 path/to/templates/layout.php
。
<html><head><title><?=$title?></title></head><body><?=$content?></body></html>
创建您的视图模板 path/to/templates/hello.php
。
Hello <?=$name?>!
在代码中渲染
$phpView = new PhpRenderer("path/to/templates", ["title" => "My App"]); $phpView->setLayout("layout.php"); //... $phpview->render($response, "hello.php", ["title" => "Hello - My App", "name" => "John"]);
响应将是
<html><head><title>Hello - My App</title></head><body>Hello John!</body></html>
请注意,$content 是在布局内使用的特殊变量,用于渲染包装的视图,不应在视图参数中设置。
异常
\RuntimeException
- 如果模板不存在
\InvalidArgumentException
- 如果 $data 包含 'template'