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