0

I include my stylesheet with a normal <link /> tag, but I need/want to access to twig variables from inside the stylesheet. Is this possible? THe only thing I imagine is putting the whole stylesheet into the document inside a <style> tag, but that won't be very pretty ;) .

2
  • You can't simply turn a CSS file in a twig file. There are many solutions, depending on the situation. What exactly would you like to do with your CSS ? Commented Jul 27, 2013 at 13:19
  • You don't need to put the whole stylesheet in a <style> tag, you can also do small css adjustments in a div tag like this: <div style="...">. Still not really pretty, but fast and simple. Commented Mar 18, 2016 at 10:15

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.