Question

In my layout.html.twig (which is the base layout used by all pages), I have the following line:

<body class="{{ render(controller('MyMainBundle:Main:bodyClass')) }}">

The problem is that I want to output different classes depending on the controller and action, but in the "bodyClassAction" method of the "Main" controller, $request->attributes->get('_controller') obviously returns MyMainBundle:Main:bodyClass.

So, right now, I'm parsing the URL ($_SERVER['REQUEST_URI']) to determine which class I should return, which isn't very clean.

Is there a way to know the "original" or "parent" controller and action?

Maybe I shouldn't use a {{ render(controller(...)) }} at all?

Was it helpful?

Solution

Good practice is depending class by route instead. Like:

<body class="
   {% if app.request.attributes.get('_route') == 'my_route' %}
       my-route-class
   {% elseif app.request.attributes.get('_route') == 'my_route1' %}
       my-route-class2
   {% endif %}
">

You could move this logic to Twig extension and got sth like taht:

<body class="{{ getBodyClass(app.request.attributes.get('_route')) }}">

And in your extenstion:

public function getFunctions() {
    return array(
        new \Twig_SimpleFunction('getBodyClass', array($this, 'getBodyClass'))
    );
}

public functiongetBodyClass($route) {
    if ($route === 'my_route_1') {
        return 'my-route-class'
    } else if ($route === 'my_route_2') {
        return 'my-route-class2'
    }
    return 'default-class';
}

OTHER TIPS

Maybe I shouldn't use a {{ render(controller(...)) }} at all?

Yep, making a sub-request for this is a bit overkill. In my point of view, using a custom twig function could be a better way to achieve your goal.

But to answer your question, you need to the controller as a parameters, something like:

{{ render(controller('MyMainBundle:Main:bodyClass', {
     'controller': app.request.get('_controller')
   })) }}

But prefer the twig function approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top