Yii2: Make Widget::end() optionally return the output

Created on 7 Feb 2017  路  6Comments  路  Source: yiisoft/yii2

Suggestion

For 2.1 I want to suggest a little change in yii\base\Widgets::end() so that we can capture a widgets output:

Use case

I had a case, where I want need to render the summary and pagination of a gridview outside the gridview widget. This is currently not so easy. With the change above we could do:

<?php $grid = GridView::begin([
    ...
    'layout' => '{items}',
]) ?>
<?php $content = GridView::end(false) ?>

<?= $grid->renderSummary() ?>
... lots of markup here ...
<?= $content ?>
... more markup here ...
<?= $grid->renderPagination() ?>

The only way to achieve something like the above right now is to use output buffering which doesn't look nice.

Required changes

  • Add an argument to Widget::end()
  • Make sure, that all yii2 widgets like GridView return their output in run() instead of echoing it. (Sidenote: I wonder why this is. I think this should be changed to make the included widgets cleaner and more in line with the documentation).

In the unlikely case that this suggestion is accepted, I could provide a PR for it.

Most helpful comment

@mikehaertl, can't your usecase be covered with the 'new' constructor instead of begin()

$grid = new Gridview(['layout' => '{items}']);
$grid->run();
...
$grid->renderSummary()

All 6 comments

I believe you can already do this with ob_start() and ob_get_contents()

@derekisbusy

The only way to achieve something like the above right now is to use output buffering which doesn't look nice.

@mikehaertl, can't your usecase be covered with the 'new' constructor instead of begin()

$grid = new Gridview(['layout' => '{items}']);
$grid->run();
...
$grid->renderSummary()

Totally agree with @dynasource

lets keep it simple and utilize the current functionality shown in example https://github.com/yiisoft/yii2/issues/13539#issuecomment-280544071

@dynasource Ah, right, thanks, that should work. Totally forgot about the most simple approach while obsessively looking at Widget::begin(), Widget::widget() and Widget::end().

Was this page helpful?
0 / 5 - 0 ratings