views中的公共代码放在一起

在views中建立一个common.php文件,然后把views中的index.php和about.php公共代码放进去

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8     <?=$content;?>
 9 </body>
10 </html>

注意:这里的 $content 没有在任何一个地方赋值

index.php中的内容为: hello index 

about.php中的内容为: hello about 

然后在controller中相应的代码为:

设定公共文件: public $layout = 'common'; 

然后使用render函数输出相应文件中的内容:

return $this->render('about');

则输出: hello about  

2、在index.php中显示about.php中的内容:

在index.php中,加上如下代码:

<?php echo $this->render('about',array('v_hello_str'=>'hello'));?>

其中 array('v_hello_str'=>'hello') 是将该数组增加上about.php中

about.php中的内容为:

hello about
<?=$v_hello_str;?>

在controller中的代码为

public $layout = 'common';
    public function actionIndex() {
        return $this->renderPartial('index');
    }

这时使用 renderPartial 和 render 效果是一样的。

输出为: hello index hello about hello 

原文地址:https://www.cnblogs.com/jacson/p/4755003.html