Symfony2:在样式表中使用 Twig 变量 [英] Symfony2: Use Twig variable in stylesheet
问题描述
我用一个普通的 <link/>
标记包含我的样式表,但我需要/想要从样式表内部访问 twig 变量.这可能吗?我唯一能想到的就是将整个样式表放入 <style>
标签内的文档中,但这不会很漂亮 ;) .
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 ;) .
推荐答案
创建一个样式表,例如 styles.css.twig
并将内容放在那里.例如:
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
)
);
}
}
将该类注册为服务并将其注册为after事件监听器(http://symfony.com/doc/current/cookbook/event_dispatcher/before_after_filters.html).
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 ).
从您的控制器(或使用方法注入的事件配置文件),您可以调用 setParam
方法来设置变量.
From your controller (or from the event config file using method injection), you can call the setParam
method to set a variable.
在您的基本 html 文件中,您可以使用它的路径(现在,web/assets/css/styles.css
)包含此文件.
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.
这篇关于Symfony2:在样式表中使用 Twig 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!