Loading View Outside View Folder with Codeigniter

Loading view outside view folder with CodeIgniter

Don't know whether it's a correct way, but it works :)

In your application/core folder put this loader extention

<?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_object_to_array($vars),
'_ci_return' => $return
));
}

}

?>

Then you want a external view file, suppose its in the third_party folder

application/third_party/my_new_view.php

Hello : <?php echo $my_name; ?>

Then call your new view in the controller

ext_view is your new view loader method,

  • 1st param : the folder inside you applicaton
  • 2nd param : the view name
  • 3rd param : the variables data and so on...

test_controller.php

$view_data = array('my_name' => 'dino');
$this->load->ext_view('third_party', 'my_new_view', $view_data);

If everything fine. it will output

Hello : dino

How do I load a view from outside the default views folder in this Codeigniter 3 application?

Here is how I solved the problem:

In application/core I have added a MY_Loader.php file with the following contents:

<?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
));
}

}

In my Posts controller's index() method, I load the view passing it the data:

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);
}

CodeIgniter - Loading View inside subfolder with Id

In the code you provided, views/administration/add_vendor_location/Id.php must exist in order to load it.

If you're trying to pass a variable to the view, you would do so using an array in the secend parameter:

$this->load->view('administration/add_vendor_location', array(
'id' => $id
));

See the CI View documentation

Codeigniter How to load view file from subfolder with multiple files

Because you are in index function so just create another function named new if you want to run localhost/test/new



Related Topics



Leave a reply



Submit