Reputation: 399
I am new to using CodeIgniter but I do have enough understanding on mvc structure and CodeIgniter itself to do simple things like load views in the controller and auto load libraries e.c.t. But the issue I'm having is I have a header and footer view that I want to be loaded automatically every time I load a view file.
I have done some searching and a lot of suggestions are dated, or sometimes I simply don't understand the solution. I have made my header view and linked my CSS in it, and also created my footer view as well. So lets say I wanted to load the default welcome page like below:
public function index() {
$this->load->view('welcome_message');
}
I can load them manually like so:
public function index() {
$this->load->view('common/header');
$this->load->view('welcome_message');
$this->load->view('common/footer');
}
But what I would like is to just load the view like normal and have my header and footer loaded with it automatically. I understand this needs to be accomplished using a custom library with a template function of some sort, but I don't know enough to just do that from scratch.
Upvotes: 1
Views: 557
Reputation: 2143
Create a core controller class called MY_Controller
and make every controller extends this controller:
class MY_Controller extends CI_Controller
{
public $data = array();
public function __construct()
{
parent::__construct();
}
public function render($view)
{
$this->view('layouts/header', $this->data);
$this->view($view, $this->data);
$this->view('layouts/footer', $this->data);
}
}
Now in your controller:
class Welcome extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->data['title'] = 'Welcome Home';
$this->render('welcome_view');
}
}
Upvotes: 1
Reputation: 156
I did this and it works for me.
MY_Loader.php
class MY_Loader extends CI_Loader{
public function template($content,$var=array()){
$this->view('common/header');
$this->view($content,$var);
$this->view('common/footer');
}
}
Put it in core
folder.
In your controller :
public function index(){
$content = "welcome_message";
$data = array();
$data['name'] = "Max";
$data['country'] = "USA";
$this->load->template($content,$data);
}
Call the data in view :
<html>
<?php echo $name.' - '.$country; ?>
</html>
Upvotes: 5