Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to change layout depending on session

Hi,

I am creating a website with general content but also some specific pages for members only. I created two layouts : common.volt and connected.volt. I would like to display the connected layout if some condition is met :

class ControllerBase extends Controller
{

    public function initialize()
    {

        if($this->session->has("userSessionID")){
            $this->view->setTemplateBefore("connected");
        }else{
            $this->view->setTemplateBefore("common");
        }

    }

}

However this doesn't work. I need to write $this->view->setTemplateBefore("connected"); in each action for the template to be displayed. What is the best way to achieve this ?

Thanks in advance.

Mathieu.



33.7k
Accepted
answer

Try using beforeExecuteRoute instead:

class ControllerBase extends Controller
{

    public function beforeExecuteRoute()
    {
        if ($this->session->has("userSessionID")) {
            $this->view->setTemplateBefore("connected");
        }else{
            $this->view->setTemplateBefore("common");
        }
    }
}

It works, thank you for your quick help :)