【问题标题】:CodeIgniter/PHP - Calling a view from within a viewCodeIgniter/PHP - 从视图中调用视图
【发布时间】:2011-02-06 17:54:52
【问题描述】:

基本上,对于我的 web 应用程序,我正在尝试更好地组织它。目前,每次我想加载一个页面时,我都必须从我的控制器中这样做:

        $this->load->view('subviews/template/headerview');
    $this->load->view('subviews/template/menuview');
    $this->load->view('The-View-I-Want-To-Load');
    $this->load->view('subviews/template/sidebar');
    $this->load->view('subviews/template/footerview'); 

正如你所见,它的效率并不高。

所以我想我会创建一个“主”视图 - 它称为 template.php。这是模板视图的内容:

<?php
    $view = $data['view'];

        $this->load->view('subviews/template/headerview');
        $this->load->view('subviews/template/menuview');
        $this->load->view($view);
        $this->load->view('subviews/template/sidebar');
        $this->load->view('subviews/template/footerview');
?>

然后我想我可以像这样从控制器调用它:

    $data['view'] = 'homecontent';
    $this->load->view('template',$data);

不幸的是,我根本无法完成这项工作。有没有人有任何方法可以解决这个问题或我可以实施的修复?我尝试在 template.php 中的 $view 周围放置 ""s 和 ',但这并没有什么区别。通常的错误是“未定义变量:数据”或“无法加载视图:$view.php”等。

谢谢各位!

杰克

【问题讨论】:

    标签: php codeigniter views


    【解决方案1】:

    这里有很多建议http://codeigniter.com/forums/viewthread/88335/

    我选择了这个方法: 控制器类:

    public function __construct() 
    {
        parent::__construct();
    
        $this->load->vars(array(
            'header' => 'partials/header',
            'footer' => 'partials/footer',
        ));
    }
    
    public function index()
    {       
        $data['page_title'] = 'Page specific title';        
        $this->load->view('my-view', $data);
    }
    

    查看:

    <?php $this->load->view($header, compact('page_title')); ?>
    ... blah blah ...
    <?php $this->load->view($footer); ?>
    

    必须在视图中加载视图并传递您的子视图可能使用的任何变量,这远非理想。能够使用像Action Filters in Laravel 这样的东西可能会更好。

    【讨论】:

      【解决方案2】:

      我相信你在哪里:

      $view = $data['view'];
      
      $this->load->view('subviews/template/headerview');
      $this->load->view('subviews/template/menuview');
      $this->load->view($view);
      $this->load->view('subviews/template/sidebar');
      $this->load->view('subviews/template/footerview');
      

      你只需要摆脱这条线:

      $view = $data['view'];
      

      这是因为当从控制器传递数组时,视图上的变量可以简单地通过$view而不是$data['view']来访问。

      【讨论】:

      • 谢谢,我试试看!我会在几分钟后报告。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 2023-03-16
      • 2015-01-23
      • 1970-01-01
      相关资源
      最近更新 更多