Loading view outside view folder with CodeIgniter

后端 未结 7 2023
悲哀的现实
悲哀的现实 2020-12-03 12:44

I have the need to load a view from outside the scope of:

$this->load->view();

which appears to work from base/application/vie

相关标签:
7条回答
  • 2020-12-03 13:26

    create a file MY_Loader.php in application/core/

    <?php
    class MY_Loader extends CI_Loader {
    
    
        function  __construct() {
            parent::__construct();
            $CI =& get_instance();
            $CI->load = $this;
        }
    
        public function ext_view($view, $vars = array(), $return = FALSE){
    
           $_ci_ext = pathinfo($view, PATHINFO_EXTENSION);
           $view = ($_ci_ext == '') ? $view.'.php' : $view;
    
           return $this->_ci_load(array(
                   '_ci_vars' =>   $this->_ci_object_to_array($vars),
                   '_ci_path' => $view, '_ci_return' => $return));
    
        }
    
    }
    

    create a file MY_Controller.php in application/core/

    <?php 
    class MY_Controller extends CI_Controller {
        public function __construct(){
            parent::__construct();
            $this->load =& load_class('Loader', 'core', 'MY_');
            $this->load->initialize();
            log_message('debug', "Controller Class Initialized");
        } 
    }
    

    Use MY_Controller instead of CI_Controller and you can access the ext_view method with

    $this->load->ext_view(path/to/the/view/file,@param2,@param3);
    

    ex:

    class Welcome extends MY_Controller {
      public function __construct() {
        parent::__construct();
      }
    
      public function index() {
        $this->load->ext_view('/path/to/view');
      }
    }
    
    0 讨论(0)
提交回复
热议问题