Symfony2:在样式表中使用Twig变量

hic*_*000 0 symfony twig

我将样式表包含在普通<link />标签中,但我需要/想要从样式表中访问twig变量.这可能吗?我想象的只是将整个样式表放入<style>标签内的文档中,但这不会很漂亮;).

Wou*_*r J 5

例如styles.css.twig,创建样式表并将内容放在那里.例如:

.user-color{
    color: {{ user_color }};
}
Run Code Online (Sandbox Code Playgroud)

现在,创建一个呈现此文件并将其保存在某处的类:

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
            )
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

将此类注册为服务并将其注册为事件后监听器(http://symfony.com/doc/current/cookbook/event_dispatcher/before_after_filters.html).

从您的控制器(或使用方法注入的事件配置文件),您可以调用该setParam方法来设置变量.

在基本html文件中,您可以使用它的路径(现在,web/assets/css/styles.css)来包含此文件.

请注意,代码就是一个例子.为了使其在生产中可用,肯定需要一些错误处理和缓存.