creating css using twig creating css using twig symfony symfony

creating css using twig


It certainly is possible. You would do most of things exactly the same as if you would do for html template.

  1. Create file, eg:

    /* src/Acme/MyBundle/Resources/views/somefile.css.twig */.someclasss {    background-color: {{ backgroundColor }};}
  2. 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']    );}// ...
  3. Create route for that action

       # src/Acme/MyBundle/Resources/config/routing.yml   css_route:       path: /some/path       defaults: { _controller AcmeMyBundle:MyStyleController:style }       methods: [GET]
  4. 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.


Actually

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']    );}

should be more like this

    /**     * @Route("/css/style", name="style")     * @param Request $request     * @return Response     */    public function styleAction(Request $request)    {        $firstColor = 'rgba(130, 30, 30, 0.9)';        /** @var Response $response */        $response = $this->render(':css:style.css.twig', [            'firstColor' => $firstColor,        ]);        $response->headers->set('Content-Type', 'text/css');        return $response;    }

Note that I have annotations because I use Symfony 3. But the important thing in my code sample is that for the response I set Content-Type to 'text/css'.