Reputation: 75
On Ci you have the possibility to load a view directly from the constructor of your controller, I'm loading the header and footer of my page (since it's the same for each function)
class Add extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->view('header_view');
$this->load->view('footer_view');
}
function whatever()
{
//do stuff
}
}
But this will load the footer view before loading my function, so is there any way to do it without "manually" loading the view at the end of each function ?
Upvotes: 2
Views: 1803
Reputation: 151
I've come up with this approach:
class Add extends CI_Controller{
public function __construct()
{
parent::__construct();
// load some static
$this->data['page_footer'] = $this->common_model->get_footer();
}
private function view_loader () {
//decide what to load based on local environment
if(isset($_SESSION['user'])){
$this->load->view('profile_view', $this->data);
} else {
$this->load->view('unlogged_view', $this->data);
}
}
function index()
{
$this->data['page_content'] = $this->profile_model->do_stuff();
// call once in every function. this is the only thing to repeat.
$this->view_loader();
}
}
Upvotes: 0
Reputation: 7902
I would add the header/footer in the main view with the data, or use a template library (I use this one).
If in main view for function;
// in view for html page
<?php $this->load->view('header'); ?>
<h1>My Page</h1>
<?php $this->load->view('footer'); ?>
Upvotes: 4
Reputation: 11552
You shouldn't be rendering any views in the constructor. CI Controllers should look more something like this:
class Add extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
}
function index()
{
$this->load->view('header_view');
$this->load->view('home_page');
$this->load->view('footer_view');
}
function whatever()
{
/*
* Some logic stuff
*/
$data_for_view = array(
'product' => 'thing',
'foo' => 'bar'
);
$this->load->view('header_view');
$this->load->view('show_other_stuff', $data_for_view);
$this->load->view('footer_view');
}
}
Upvotes: 0