yiisoft/yii-view-renderer
Composer 安装命令:
composer require yiisoft/yii-view-renderer
包简介
PSR-7 compatible view renderer
README 文档
README
Yii View Renderer
The package is an extension of the Yii View rendering library. It adds WEB-specific functionality and compatibility with PSR-7 interfaces.
Requirements
- PHP 8.1 - 8.5.
Installation
The package could be installed with Composer:
composer require yiisoft/yii-view-renderer
General usage
There are two ways to render a view:
- Return an instance of
Psr\Http\Message\ResponseInterfacewith deferred rendering. - Render immediately and return the rendered result as a string.
Rendering result as a PSR-7 response
You can get an instance of a response with deferred rendering as follows:
/** * @var \Psr\Http\Message\ResponseFactoryInterface $responseFactory * @var \Psr\Http\Message\StreamFactoryInterface $streamFactory * @var \Yiisoft\Aliases\Aliases $aliases * @var \Yiisoft\View\WebView $webView */ $viewRenderer = new \Yiisoft\Yii\View\Renderer\WebViewRenderer( $responseFactory, $streamFactory, $aliases, $webView, '/path/to/views', // Full path to the directory of view templates or its alias. 'layouts/main.php', // Default is null, which means not to use a layout. ); // Rendering a view with a layout. $response = $viewRenderer->render('site/page', [ 'parameter-name' => 'parameter-value', ]);
The rendering will be performed directly when calling the getBody() method of the response.
If a layout is set, but you need to render a view without the layout, you can use an immutable setter withLayout():
$viewRenderer = $viewRenderer->withLayout(null); // Rendering a view without a layout. $response = $viewRenderer->render('site/page', [ 'parameter-name' => 'parameter-value', ]);
Or use renderPartial() method, which will call withLayout(null):
// Rendering a view without a layout. $response = $viewRenderer->renderPartial('site/page', [ 'parameter-name' => 'parameter-value', ]);
Rendering result as a string
To render immediately and return the rendering result as a string,
use renderAsString() and renderPartialAsString() methods:
// Rendering a view with a layout. $result = $viewRenderer->renderAsString('site/page', [ 'parameter-name' => 'parameter-value', ]); // Rendering a view without a layout. $result = $viewRenderer->renderPartialAsString('site/page', [ 'parameter-name' => 'parameter-value', ]);
Change view templates path
You can change view templates path in runtime as follows:
$viewRenderer = $viewRenderer->withViewPath('/new/path/to/views');
You can specify full path to the views directory or its alias. For more information about path aliases, see description of the yiisoft/aliases package.
Use in the controller
If the view renderer is used in a controller, you can either specify controller name explicitly using
withControllerName() or determine name automatically by passing a controller instance to withController().
In this case the name is determined as follows:
App\Controller\FooBar\BazController -> foo-bar/baz
App\Controllers\FooBar\BazController -> foo-bar/baz
App\AllControllers\MyController\FooBar\BazController -> foo-bar/baz
App\AllControllers\MyController\BazController -> baz
Path\To\File\BlogController -> blog
With this approach, you do not need to specify the directory name each time when rendering a view template:
use Psr\Http\Message\ResponseInterface; use Yiisoft\Yii\View\Renderer\WebViewRenderer; class SiteController { private WebViewRenderer $viewRenderer; public function __construct(WebViewRenderer $viewRenderer) { // Specify the name of the controller: $this->viewRenderer = $viewRenderer->withControllerName('site'); // or specify an instance of the controller: //$this->viewRenderer = $viewRenderer->withController($this); } public function index(): ResponseInterface { return $this->viewRenderer->render('index'); } public function contact(): ResponseInterface { // Some actions. return $this->viewRenderer->render('contact', [ 'parameter-name' => 'parameter-value', ]); } }
This is very convenient if there are many methods (actions) in the controller.
Injection of additional data to the views
In addition to parameters passed directly when rendering the view template, you can set extra parameters that will be available in all views. In order to do it you need a class implementing at least one of the injection interfaces:
use Yiisoft\Yii\View\Renderer\CommonParametersInjectionInterface; use Yiisoft\Yii\View\Renderer\LayoutParametersInjectionInterface; final class MyParametersInjection implements CommonParametersInjectionInterface, LayoutParametersInjectionInterface { // Pass both to view template and to layout public function getCommonParameters(): array { return [ 'common-parameter-name' => 'common-parameter-value', ]; } // Pass only to layout public function getLayoutParameters(): array { return [ 'layout-parameter-name' => 'layout-parameter-value', ]; } }
Link tags and meta tags should be organized in the same way.
use Yiisoft\Html\Html; use Yiisoft\View\WebView; use Yiisoft\Yii\View\Renderer\LinkTagsInjectionInterface; use Yiisoft\Yii\View\Renderer\MetaTagsInjectionInterface; final class MyTagsInjection implements LinkTagsInjectionInterface, MetaTagsInjectionInterface { public function getLinkTags(): array { return [ Html::link()->toCssFile('/main.css'), 'favicon' => Html::link('/myicon.png', [ 'rel' => 'icon', 'type' => 'image/png', ]), 'themeCss' => [ '__position' => WebView::POSITION_END, Html::link()->toCssFile('/theme.css'), ], 'userCss' => [ '__position' => WebView::POSITION_BEGIN, 'rel' => 'stylesheet', 'href' => '/user.css', ], ]; } public function getMetaTags(): array { return [ Html::meta() ->name('http-equiv') ->content('public'), 'noindex' => Html::meta() ->name('robots') ->content('noindex'), [ 'name' => 'description', 'content' => 'This website is about funny raccoons.', ], 'keywords' => [ 'name' => 'keywords', 'content' => 'yii,framework', ], ]; } }
You can pass instances of these classes as the sixth optional parameter to the constructor when
creating a view renderer, or use the withInjections() and withAddedInjections methods.
$parameters = new MyParametersInjection(); $tags = new MyTagsInjection(); $viewRenderer = $viewRenderer->withInjections($parameters, $tags); // Or append it: $viewRenderer = $viewRenderer->withAddedInjections($parameters, $tags);
The parameters passed to render() method have more priority
and will overwrite the injected content parameters if their names match.
Injections lazy loading
You can use lazy loading for injections. Injections will be created by container that implements
Yiisoft\Yii\View\Renderer\InjectionContainerInterface. Out of the box, it is available in InjectionContainer that is based on PSR-11 compatible
container.
- Add injection container to
WebViewRendererconstructor:
use Yiisoft\Yii\View\Renderer\WebViewRenderer; use Yiisoft\Yii\View\Renderer\InjectionContainer\InjectionContainer; /** * @var Psr\Container\ContainerInterface $container */ $viewRenderer = new WebViewRenderer( injectionContainer: new InjectionContainer($container) )
- Use injection class names instead of instances.
$viewRenderer->withInjections(MyParametersInjection::class, MyTagsInjection::class);
Localize view file
You can set a specific locale that will be used to localize view files with withLocale() method:
$viewRenderer = $viewRenderer->withLocale('de_DE');
For more information about localization, see at the localization section in yiisoft/view package.
Yii Config parameters
'yiisoft/yii-view-renderer' => [ // The full path to the directory of views or its alias. // If null, relative view paths in `WebViewRenderer::render()` is not available. 'viewPath' => null, // The full path to the layout file to be applied to views. // If null, the layout will not be applied. 'layout' => null, // The injection instances or class names. 'injections' => [], ],
Documentation
If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.
License
The Yii View Renderer is free software. It is released under the terms of the BSD License.
Please see LICENSE for more information.
Maintained by Yii Software.
Support the project
Follow updates
yiisoft/yii-view-renderer 适用场景与选型建议
yiisoft/yii-view-renderer 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 83.05k 次下载、GitHub Stars 达 17, 最近一次更新时间为 2024 年 06 月 17 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「view」 「renderer」 「yii」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 yiisoft/yii-view-renderer 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 yiisoft/yii-view-renderer 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 yiisoft/yii-view-renderer 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Shoot aims to make providing data to your templates more manageable
Yii2 LightBox image galary widget uses Lightbox v2.10.0 by Lokesh Dhakar
Bootstraps errors and handles them via reporters and renderers
Illuminate View for Morningmedley.
Priveate for SkeekS CMS
Blade template for Kirby
统计信息
- 总下载量: 83.05k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 17
- 点击次数: 29
- 依赖项目数: 23
- 推荐数: 2
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2024-06-17