codespede / yii2-template-renderer
该包最新版本(1.0.1)的许可证信息不可用。
使用父视图、子视图和数据提供者,在任意自定义格式/结构中渲染数据的功能。
1.0.1
2018-10-20 15:56 UTC
Requires
- php: >=5.4.0
- yiisoft/yii2: *
This package is auto-updated.
Last update: 2024-09-29 04:07:52 UTC
README
通过仅使用父视图、子视图和数据提供者,方便地以任意自定义格式/结构渲染数据(支持分页、排序、过滤以及数据提供者支持的所有其他操作)。
尽管此扩展主要针对在Yii 2中构建的RESTful API,但它可以像下面解释的那样在应用程序的任何地方使用。
安装
安装此扩展的首选方式是通过composer。
运行以下命令:
php composer.phar require codespede/yii2-template-renderer "*"
或者在composer.json的require部分添加以下内容:
"codespede/yii2-template-renderer": "*"
to the require section of your composer.json.
使用场景
- 假设您想要以如下CSV格式提供数据
title,image,content
ABC,abc.jpg,Content of ABC
MNO,mno.jpg,Content of MNO
XYZ,xyz.jpg,Content of XYZ
- 假设您必须以如下特定格式渲染API响应
-begin-
--title=ABC
--image=abc.jpg
--content=Content of ABC
---
--title=MNO
--image=mno.jpg
--content=Content of MNO
---
--title=XYZ
--image=xyz.jpg
--content=Content of XYZ
-end-
- 或者在任何您需要通过API提供自定义格式数据的情况下。
如何使用
可以通过在任何操作中简单地返回TemplateRenderer对象来使用此功能,如下所示:
public function actionRender(){
$dataProvider = new ActiveDataProvider(['query' => Model::find()->where($condition)])
return new \cs\templaterenderer\TemplateRenderer([
'dataProvider' => $dataProvider,
'parentView' => '/path/to/parent-view', //path to the parent or wrapper view file
'itemView' => '/path/to/item-view', //path to the item view file
]);
}
在$parentView文件中,代码中的占位符{{items}}将被自动替换为当前页面上模型的$itemView的渲染结果。例如,如果内容需要像上面第二个使用场景中那样渲染,那么$parentView文件应该是这样的:
-begin-
{{items}}
-end-
而$itemView应该是这样的:
--title=<?=$model->title?>
--image=<?=$model->image?>
--content=<?=$model->content?>
优点
- 数据可以像使用GridView或ListView一样进行分页、排序和过滤。您可以在URL中传递分页、排序和过滤参数,渲染的内容将根据提供的参数进行。
- 通过在响应中利用分页头,可以轻松地在分页内容中导航。