Вопрос

reading symfony documentation about templating I found mention about twig being able to output css files.

how is this used? is it possible to generate dynamic css same way as I generate html?

for example when I want to display some html template I create controller action and inside I render .html.twig file possibly passing it some parameters.

can I render .css.twig same way? where would be this file stored and how could I possibly include it to another html template.

I would like to keep all styles in separate files, but some of these styles change under some conditions. for example, right now I'm setting height of some divs according to calculations in controller and I pass result height as parameter to template. but I don't feel like this is very MVC, having part of representation logic in controller (or even model).

Это было полезно?

Решение

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'.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top