【问题标题】:How do I load a view from outside the default views folder in this Codeigniter 3 application?如何从 Codeigniter 3 应用程序的默认视图文件夹之外加载视图?
【发布时间】:2025-11-27 00:15:02
【问题描述】:

我正在使用 CodeIgniter 3.1.8 和 Bootstrap 4 开发 CMS。我决定为其添加主题。该应用程序不是 HMVC,只有 MVC。

themes 目录位于 application 之外,如下图所示:

themes 我有一个主题目录(当然),其中包含“主视图”layout.php:

application/core我添加了一个Loader.php文件,内容如下:

<?php defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH."../system/core/Loader.php";

    class MY_Loader extends CI_Loader {
    
      function ext_view($folder, $view, $vars = array(), $return = FALSE) {
        $this->_ci_view_paths = array_merge($this->_ci_view_paths, array(APPPATH . $folder . '/' => TRUE));
        return $this->_ci_load(array(
                '_ci_view' => $view,
                '_ci_vars' => $this->_ci_prepare_view_vars($vars),
                '_ci_return' => $return
            ));
      }
    
}?>

在我的 Posts 控制器的 index() 方法中,我加载视图并传递数据:

public function index() {
    //more code here
     $this->load->ext_view('third_party', 'themes/caminar/layout', $data);
}

我收到此错误消息:

Call to undefined method CI_Loader::ext_view();

我做错了什么?

【问题讨论】:

标签: php codeigniter codeigniter-3


【解决方案1】:

这是我解决问题的方法:

application/core我添加了一个MY_Loader.php文件,内容如下:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

  class MY_Loader extends CI_Loader {

    function theme_view($folder, $view, $vars = array(), $return = FALSE) {
      $this->_ci_view_paths = array_merge($this->_ci_view_paths, array(FCPATH . $folder . '/' => TRUE));
      return $this->_ci_load(array(
              '_ci_view' => $view,
              '_ci_vars' => $this->_ci_prepare_view_vars($vars),
              '_ci_return' => $return
          ));
    }

}

在我的 Posts 控制器的 index() 方法中,我加载视图并传递数据:

public function index() {
   //more code here
   $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
    $this->load->theme_view('/themes/caminar/', 'layout', $data);
}

【讨论】: