Reputation: 573
I'm building a website with CI, using a simple template system.
This is my basic template:
$this->load->view('includes/header');
$this->load->view($main_content);
$this->load->view('includes/footer');
I have a set of variables I want to pass to my views, and I know I can do it like this:
$data['title'] = 'title goes here';
$data['main_content'] = 'name of page goes here';
$this->load->view('template', $data);
So far - so good. But I want the above set of variables to have default values, so I won't have to declare the whole set every time I load my template.
The solution I came up with was declaring public static variables under my main controller, like so:
public static $default_data = array(
'title' => 'Generic Title Goes Here',
'main_content' => 'home_view'
);
Then I can load my views like this:
$data = Home::$default_data;
$data['main_content'] = 'member_login_view'; // I can now declare only the relevant variables. all the rest will have the default values
$this->load->view('includes/template', $data);
This method is working fine, but I have one problem with it: some of the variables I'd like to set as default are not static. For example, in the header I have a stats line showing the number of registered users on my website, and the number of products in my database. So I call it with
$data['stats'] = $this->products_model->get_stats();
Is there a way set default values to such variables, so I won't have to call the method in the model before each page load?
Upvotes: 3
Views: 3832
Reputation: 573
Found a solution. Hope it's a good one. Writing it down hoping it might help someone else.
I extended the main controller, and put all the common variables there - the static and the dynamic. I declared them as protected, so they are available to me across all views.
This is application/core/MY_Controller.php
:
class Home_Controller extends CI_Controller {
//Class-wide variable to store stats line
protected $stats;
protected $title;
protected $main_content;
public function __construct() {
parent::__construct();
//Put stats in Class-wide variable
$this->stats = $this->products_model->get_stats();
//Store stats in $data
$data->stats = $this->stats;
$data->title = 'Generic Website title';
$data->main_content = 'home_view';
//Load variables in all views
$this->load->vars($data);
}
}
And I changed the first line of my main controller to class Home extends Home_Controller
instead of class Home extends CI_Controller
.
Upvotes: 8