首页 文章

Yii无法将变量传输到布局

提问于
浏览
0

我在Yii新手,并有一些麻烦 . 我的第一个问题:我的观点没有显示 .

查看(新闻/的index.php):

<p>Hi</p>

第二个问题:我无法将变量从数据库传输到我的布局(layouts / main.php)或视图(观察第一个问题) . 我的控制器:

<?php

   class NewsController extends Controller
   {

    public function actionIndex()
    {  

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


}

来自main.php(layouts / main.php):

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

或者我试图在视图news / index.php中获取变量:

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

谢谢你的帮助 .

2 回答

  • 0

    我认为你的问题是$ layout变量布局是错误的 .

    1.如果你想在布局中使用$ result . 您必须在NewsController上创建一个全局变量 . 并在行动中为其设定 Value .

    Controller:

    <?php
        //controller: NewsController 
        class NewsController extends Controller
        {
          public $result;
    
          public function actionIndex(){
            $this->result = News::model()->findAll();
            $this->render('index');
          }
        }
    

    View:

    <!-- 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变量,请查看您的操作

    Controller:

    <?php
    class NewsController extends Controller
    {
       public function actionIndex(){
    
         $result = News::model()->findAll();
         $this->render('index', array('result'=>$result));
       }
    } ?>
    

    View:

    <!-- 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>
    
  • 1

    如果您希望布局从变量加载值 . 如果用户已登录 .

    您可以使用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.
    ?>
    

相关问题