我希望我理解了这个问题。我假设您正在寻找一种方法来根据数据库中的设置“绑定”正确的样式表,后者已经解决了
Twig 提供了类似 OOP 的继承,您可以利用它来完成这项工作。
这里分三步解决:
第一步:编写一个“主题感知”动作。在控制器中
...
public function adminAction(){
//get the settings information, this is hardcoded for the sake of esample
//you may as well fetch this from the DB
$themeSettings = array('style'=>'blue');
//render the template and inject the variable
return $this->render('AdminPageBundle:Default:template.html.twig',
array('theme'=>$themeSettings));
}
Step2 : 创建一个带有默认主题的基本模板(故障安全)
//我们称之为base.html.twig
<!DOCTYPE html>
<html>
<head>
...
{% block stylesheets %}
<link href="{{ asset('css/themes/default.css') }}" rel="stylesheet" type="text/css"/>
{% endblock %}
....
</head>
...
第 3 步:覆盖主题感知模板中的“样式表”块
//template.html.twig:
{# make it a child of base.html.twig #}
{% extends '::base.html.twig' %}
{# override the stylesheets block #}
{% block stylesheets %}
{# include what you already have in the parent template (link to default.css) #}
{{ parent }}
{# add your own theme from the database (using the 'theme' variable from the controller #}
<link href="{{ asset('css/themes/'~ theme.style ~ '.css') }}" rel="stylesheet" type="text/css"/>
{% endblock %}
在此示例中,渲染“template.html.twig”将在“/css/themes/blue.css”加载样式表。
您也可以直接在基本模板中实现这一点,而不依赖于继承,但我假设有些模板是主题感知的,而有些则不是。继承提供了仅在您需要的地方实现此功能的灵活性。
当然,还有其他几种解决问题的方法。 Writing a custom twig extension 处理主题对于可靠的长期解决方案来说是正确的做法,尤其是在主题不仅仅是加载样式表的情况下。您还可以编写一个事件处理程序(用于 kernel.view 事件)以在渲染之前修改模板或注入主题设置。 This answer 显示了一个示例。