Symfony2: Use Twig variable in stylesheet

前端 未结 1 581
误落风尘
误落风尘 2021-01-27 13:05

I include my stylesheet with a normal tag, but I need/want to access to twig variables from inside the stylesheet. Is this possible? THe only thing I

相关标签:
1条回答
  • 2021-01-27 13:35

    Create a stylesheet, for instance styles.css.twig and put the content there. For instance:

    .user-color{
        color: {{ user_color }};
    }
    

    Now, create a class which renders this file and saves it somewhere:

    class TemplateRenderer
    {
        protected $basepath;
        protected $templating;
        protected $parameters = array();
    
        public function __construct($templating, $basepath, $styleseheetpath)
        {
            $this->basepath = $basepath; /* "%kerel.base_path" parameter */
            $this->templating = $templating; /* "twig" service */
            $this->stylesheetpath = $stylesheetpath; /* custom defined parameter */
        }
    
        public function setParam($id, $value)
        {
            $this->parameters[$id] = $value;
        }
    
        public function render()
        {
            file_put_contents(
                $this->basepath.'/web/assets/css/styles.css',
                $this->templating->render(
                    $this->stylesheetpath,
                    $this->parameters
                )
            );
        }
    }
    

    Register this class as a service and register it as an after event listener (http://symfony.com/doc/current/cookbook/event_dispatcher/before_after_filters.html ).

    From your controller (or from the event config file using method injection), you can call the setParam method to set a variable.

    Inside your base html file, you can include this file using it's path (now, web/assets/css/styles.css).

    Please note that the code is an example. Some error handling and caching is definitely needed to make this usable in production.

    0 讨论(0)
提交回复
热议问题