A Very Simple Theme Switcher for Codeigniter
June 15, 2011
I am using this library for all of my Codeigniter projects and I was thinking how to dynamically change the theme of the website.
My first thought was to dynamically change the “views” of CI_Loader but it seems to be very hard to do without editing the Core.
Codeigniter doesn’t actually let you extend the Core by using hooks but extending the library ( which is confusing when you read the documentation).
/system/core/Loader.php
function __construct()
{
$this->_ci_view_path = APPPATH.'views/';
$this->_ci_ob_level = ob_get_level();
$this->_ci_library_paths = array(APPPATH, BASEPATH);
$this->_ci_helper_paths = array(APPPATH, BASEPATH);
$this->_ci_model_paths = array(APPPATH);
log_message('debug', "Loader Class Initialized");
}
Note that the views folder is hard-coded. I would suggest to have ci_view_path to be on of the config items.
But anyway by using the library of Jerome (http://maestric.com/doc/php/codeigniter_template) , you can easily achieve a dynamic theme without changing it. Below is the code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Template {
var $template_data = array();
function set($name, $value)
{
$this->template_data[$name] = $value;
}
function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
{
$this->CI =& get_instance();
$user_template = isset($_SESSION['template']) ? $_SESSION['template'] : 'default';
$this->set('contents', $this->CI->load->view($user_template.'/'.$view, $view_data, TRUE));
return $this->CI->load->view($user_template.'/'.$template, $this->template_data, $return);
}
}
Now, you have a theme inside the views folder..
/application/views/default/
/application/views/theme1/
/application/views/theme2/
Simple right!




