官术网_书友最值得收藏!

  • Yii2 By Example
  • Fabrizio Caldarelli
  • 300字
  • 2021-07-16 19:38:55

Splitting the common view content into reusable views

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.

Example – render partial in view

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.

Note

Usually, in Yii2's app, a view name that starts with underscore stands for common reusable view.

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.

Note

Pay attention! Since renderPartial() is a method of the Controller class and $this refers to the View class in the view file, to access from $this to renderPartial() we will use the context member, which represents the Controller object in the View object.

主站蜘蛛池模板: 元朗区| 卢湾区| 隆德县| 湛江市| 虹口区| 黎城县| 寿阳县| 郸城县| 长武县| 黎城县| 青阳县| 旅游| 拉萨市| 子长县| 长乐市| 荣昌县| 元朗区| 惠州市| 宝山区| 兴宁市| 永修县| 安徽省| 浠水县| 永春县| 东台市| 嘉禾县| 南郑县| 灵台县| 梁平县| 凤台县| 宜州市| 鄂托克旗| 安康市| 沁阳市| 铅山县| 河曲县| 红安县| 隆昌县| 敦煌市| 赣州市| 绥滨县|