我包括带有普通<link />标记的样式表,但我需要/希望访问样式表内部的twig变量。这个是可能的吗?THe唯一能想到的就是将整个样式表放入<style>标记中的文档中,但这并不是很好;)。
发布于 2013-07-27 14:02:49
创建一个样式表,例如styles.css.twig,并将内容放在那里。例如:
.user-color{
color: {{ user_color }};
}现在,创建一个类来呈现该文件并将其保存在某个地方:
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
)
);
}
}将该类注册为服务,并将其注册为事后事件侦听器(filters.html )。
从控制器(或使用方法注入的事件配置文件),您可以调用setParam方法来设置变量。
在您的基本html文件中,可以使用它的路径(现在是web/assets/css/styles.css)来包含这个文件。
--请注意,代码就是一个例子。为了使其在生产中可用,肯定需要一些错误处理和缓存。
https://stackoverflow.com/questions/17897950
复制相似问题