views中的公共代码放在一起

时间:2023-03-09 23:55:32
views中的公共代码放在一起

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

 <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?=$content;?>
</body>
</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