yii怎么往模板里传变量

2020-08-24 11:51:05

添加动态内容最简单的方法,就是在视图模板文件中嵌入PHP语句。任何在<?php和?>标签之间的代码会作被执行。 (推荐学习:yii教程)

<h3><?php echo date("D M j G:i:s T Y"); ?></h3>

将业务逻辑放到控制器中,使我们的业务逻辑与视图分离控制器文件中:

$theTime=date("D M j G:is T Y");$this->render('helloWorld',array('time'=>$theTime));

视图文件中:

<h3><?php echo $time; ?></h3>

视图与控制器是非常紧密的兄弟,所以视图文件中的$this指的就是渲染这个视图的控制器。

在控制器中定义一个类的公共属性,而不是局部变量。然后在视图中通过$this访问这个类的属性。

class MessageController extends Controller {    public $time;    public function actionHelloworld() {           $this->time = date("D M j G:is T Y");       $this->render('helloworld', array('time' => $theTime));    }


视图文件中:

<h3><?php echo $this->time; ?></h3>
相关文章 大家在看