If you use the template controller in Kohana PHP you may need to override the default template you specified at some stage. This is extremely easy, but it is not documented anywhere, so I thought it might be a good idea to show you.

Normally you would specify the default template like this:

<?php
class Home_Controller extends Template_Controller
{
    public $template = 'my_template';
    ...
}

Now lets suppose you are developing a mobile version of your site and you would like to use a different template for whatever reason. In your index() function you would have something like this:

<?php
class Home_Controller extends Template_Controller
{
    public $template = 'my_template';
    ...
    public function index()
    {
        if ($is_mobile) {
            //Use a different mobile template
            $this->template = new View("mobile_template");
            ...
        } else {
            //Do the normal thing and let it
            //auto generate the page and use my_template
            ...
        }
    }
}

In effect, all you need to do is to override your default specified “my_template” by assigning a new View object which would be a different template that does what you need it to do.

Another way of doing it is as follows:

<?php
class Home_Controller extends Template_Controller
{
    public $template = 'my_template';

    public function __construct()
    {
        if ($is_mobile) {
            $this->template = 'mobile_template';
        }
        parent::__construct();
    }
...
}

Assign your new template to the variable in your controller’s constructor before you call the parent class (Template_Controller) constructor. The Template_Controller does the following in it’s constructor, FYI:

$this->template = new View($this->template);

If you do the following, it would #FAIL:

<?php
class Home_Controller extends Template_Controller
{
    public $template = 'my_template';

    public function __construct()
    {
        parent::__construct();
        if ($is_mobile) {
            $this->template = 'mobile_template';
        }
    }
...
}

If its not obvious to you, what happens is that in the Template_Controller constructor it assigns the my_template View object to the $this->template variable and if you assign ‘mobile_template’ to it after the Template_Controller constructor was called, you effectively override $this->template with a string called ‘mobile_template’. Very effectively… ;-)

There! I hope this helps someone somewhere.

Welcome back! You should subscribe to my RSS feed here.
You should follow me on Twitter here
You should follow me on Gatorpeeps here.