We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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.



34.6k
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 :)