Can i change the $Layout from controller?

Silverstripe Version: 4.9

Question: Can i change the $Layout from Controller?

Hello, I have a question about loading layout. There is any way for change the value of $Layout variable? for example i have a page with some specific params and i want to load different Layout for each params. For better understanding I have ?param=1 or ?param=2 And my goal is to have the same template but only modify $Layout between:

themes/mysite/templates/Layout/FirstLayout.ss
themes/mysite/templates/Layout/SecondLayout.ss

Maybe it’s easier to change the whole template for this controller i mean Page.ss and NumberLayout.ss

i was thinking about something like this

    $SSViewer = new SSViewer();
    if (param1) {
        $SSViewer->setTemplateFile('Layout','themes/mysite/templates/Layout/FirstLayout.ss');
    } else {
        $SSViewer->setTemplateFile('Layout','themes/mysite/templates/Layout/SecondLayout.ss');
    }

But i didint know how to download SSViewer in controller and change his $Layout variable
maybe there is another way to achive this…

https://api.silverstripe.org/4/SilverStripe/View/SSViewer.html#method_setTemplateFile

Or should i use it in index.php in root directory?

Anyway, thanks for help
Have a nice day! :slight_smile:

The quick and dirty way (which answers your specific question) is to do something like:

$this->Layout = $this->renderWith('path/to/template.ss');
...
....

return $this->render();

But how messy that gets will depend a lot on what data you have and how you’re rendering it to the template…

If you can use URL parameters rather than request params, then it becomes much simpler… so you’d have:

example.com/somepage/somelayout
example.com/somepage/alternatelayout

You can then just structure your template files like this:

MyPage.ss
MyPage_somelayout.ss
MyPage_alternatelayout.ss

Silverstripe will match the bit after the underscore against the method names in the controller, eg:

class MyPageController extends PageController
{
  private static $allowed_actions = [
    'somelayout',
    'alternatelayout'
  ];

  public function index()
   {
     //The default layout (MyPage.ss)
    return $this->render();
   }

  public function somelayout()
  {
    //The MyPage_somelayout.ss file
    return $this->render();
  }

  public function alternatelayout()
  {
    //The MyPage_alternatelayout.ss file
    return $this->render();
  }
}

Ok, thats work but anyway how can i use this function from SSViewer class

https://api.silverstripe.org/4/SilverStripe/View/SSViewer.html#method_setTemplateFile

or where i should do this? in controller or somewhere else?