Sometimes, views share the same common portion of content. In the examples made until now, we have seen that a common area for itemsList
and itemDetail
could be copyright data, which displays a disclaimer about copyright info.
In order to make this, we must put the common content in a separate view and call it using the renderPartial()
method of controller (http://www.yiiframework.com/doc-2.0/yii-base-controller.html#renderPartial%28%29-detail). It has the same types of parameters of the render()
method; the main difference between the render()
and renderPartial()
methods is that render()
writes a view content in layout and renderPartial()
writes only view contents to output.
In this example, we create a common view for both itemsList
and itemDetail
about copyright data.
Create a view file named _copyright.php
in views/news
.
In this file, put only a text for copyright into views/news/_copyright.php
:
<div> This is text about copyright data for news items </div>
Now, we want to display this view inside the itemsList
and itemDetail
views.
Change the content in itemsList.php
located at views/news/
as follows:
<?php echo $this->context->renderPartial('_copyright'); ?> <table> <tr> <th>Title</th> <th>Date</th> </tr> <?php foreach($newsList as $item) { ?> <tr> <th><a href="<?php echo Yii::$app->urlManager->createUrl(['news/item-detail' , 'id' => $item['id']]) ?>"> <?php echo $item['title'] ?> </a></th> <th><?php echo Yii::$app->formatter->asDatetime($item['date'], 'php:d/m/Y'); ?></th> </tr> <?php } ?> </table>
Then, change the content in itemDetail.php
located at views/news/
as follows:
<?php // $item is from actionItemDetail ?> <?php echo $this->context->renderPartial('_copyright'); ?> <h2>News Item Detail<h2> <br /> Title: <b><?php echo $item['title'] ?></b> <br /> Date: <b><?php echo $item['date'] ?></b>
We have put a common code at the top of the file in both views:
<?php echo $this->context->renderPartial('_copyright'); ?>
This will render the content of the _copyright.php
view without layout.
3.136.233.153