JohnSmith
JohnSmith

Reputation: 462

Set Twig layout in controller

I have multiple subdomains, each with its own layout. Some controllers are shared across subdomains (e.g login), some not. What I'd like to do is to set layout according to domain, so that I would not need to write in each template:

{% if app.request.domain == 'one' %}
  {% set layout = '::layout-one.html.twig' %}
{% elseif app.request.domain == 'two' %}
  {% set layout = '::layout-two.html.twig' %}
...
{% endif %}
{% extends layout %}

Is it possible to set default layout in controller (or somewhere)? E.g:

class FooController 
{
    function fooAction()
    {
        ...
        $templating = $this->get('templating');
        $templating->setLayout($layout);
        return $templating->renderResponse($view, $parameters, $response);
    }
}

Upvotes: 1

Views: 1063

Answers (2)

chapay
chapay

Reputation: 1315

You can set layout variable in your FooController:

class FooController 
{
    function fooAction()
    {
        ...
        return $this->render($template, array(
            'layout' => $layout
        ));
    }
}

And then use it in your template:

{% extends layout %}

Upvotes: 1

Stian Martinsen
Stian Martinsen

Reputation: 654

If you have a separate config file for each of the domains, you can put the layout config in there and have it available in twig as a global variable:

config_one.yml

twig:
    globals:
        base_layout: '::layout-one.html.twig'

Then in twig you can just do:

{% extends base_layout %}

Upvotes: 3

Related Questions