It certainly is possible. You would do most of things exactly the same as if you would do for html template.
Create file, eg:
/* src/Acme/MyBundle/Resources/views/somefile.css.twig */ .someclasss { background-color: {{ backgroundColor }}; }
Create controller action
// src/Acme/MyBundle/Controller/MyStyleController.php // ... public function styleAction() { // Fetch it from service or whatever strategy you have $backgroundColor = '#ff0000'; return $this->render( 'AcmeMyBundle::somefile.css.twig', ['backgroundColor' => $backgroundColor], ['Content-Type' => 'text/css'] ); } // ...
Create route for that action
# src/Acme/MyBundle/Resources/config/routing.yml css_route: path: /some/path defaults: { _controller AcmeMyBundle:MyStyleController:style } methods: [GET]
Use that css in your layout
{# src/AcmeMyBundle/Resources/views/mypage.html.twig #} {# ... #} <link href="{{ path('css_route') }}" rel="stylesheet"> {# ... #}
Now, whether or not this is a good idea should be a separate question. There certainly are some cases where this approach is perfectly valid, but there are cases where you can avoid this. Keep in mind that serving CSS file like this is a lot more expensive than serving static CSS file. Furthermore, since it's a CSS file and it's in HEAD section of your response, it will slow down page load time since it will have to fetch CSS file before rendering body itself.
If you do decide to do this be sure to check out caching possibilities you have to make this as fast as possible.