2014-02-11 23 views
0

即时通讯新手,并有一些麻烦。 我的第一个问题: 我的视图没有显示任何内容。Yii无法传输变量来布局

视图(新闻/ index.php文件):

<p>Hi</p> 

问题二: 我不能传递从数据库变量我的布局(布局/ main.php)或视图(看第一个问题)。 我的控制器:

<?php 

    class NewsController extends Controller 
    { 

    public function actionIndex() 
    { 

    $result = News::model()->findAll('id'); 
    $this->render('index', array('result'=>$result)); 
    } 


} 

从main.php(布局/ main.php):

<div id = "content"> 
    <?php 
    echo $content; 
    echo $result; //or $this->mydatafrombase; 
    ?> 
    </div> 

或IM试图让变量鉴于新闻/ index.php文件:

<p>Hi</p> 
<?php 
echo $this->mydatafrombase; 
?> 

感谢您的帮助。

+0

不要使用'$ this'从控制器访问变量。你可以通过添加一个'$'来访问它们:''result''在你的视图中变成'$ result'。 – Michiel

回答

1

我认为你的问题是$结果变量在布局是错误的。

1.如果要在布局中使用$ result。您必须在NewsController中创建一个全局变量。并在行动中为其设定价值。

控制器:

<?php 
    //controller: NewsController 
    class NewsController extends Controller 
    { 
     public $result; 

     public function actionIndex(){ 
     $this->result = News::model()->findAll(); 
     $this->render('index'); 
     } 
    } 

查看:

<!-- layout.php--> 
<div id="content"> 
<?php 
    echo $content; //content of view of your action will be render at here 
    var_dump($this->result); // variable global of class NewsController 
?> 
</div> 

2.如果你想用户$ result变量在看你的行动

控制器:

<?php 
class NewsController extends Controller 
{ 
    public function actionIndex(){ 

    $result = News::model()->findAll(); 
    $this->render('index', array('result'=>$result)); 
    } 
} ?> 

查看:

<!-- news/index.php --> 
<p>Hi</p> 
<?php 
    var_dump($result); 
?> 

<!-- layout.php.--> 
<div id="content"> 
<?php 
    echo $content; //content of view of your action will be render at here 
?> 
</div> 
+0

感谢您的帮助。您的第一个建议工作正常,但我不知道如何执行此数组中的数据。例如,news_title。和第二个建议不起作用,我现在不是为什么,也许是因为即时通讯使用不默认布局? – user3266912

+0

你不使用默认布局?.. $布局是CController类的属性。因此,您可以在您的操作中定义它们:$ this-> layout ='new'。文件视图:layouts/new.php – VoVietTue

0

如果您想布局加载自变量的值。并且如果用户已登录。

您可以使用CWebUser :: setState()和CWebUser :: getState();

CController :: render()只将变量传递给index.php。

你的情况。只需将$ result放入index.php

<?php 
echo $result;//echo $this->mydatafrombase; 
//yes simply $result would work. not $this->result. $this in this context refer to NewsController. 
?>