问题描述
我想在 Symfony2 项目的树枝模板中嵌入不同的带有资产的样式表文件.使用的样式表取决于用户的主题设置.
I want to embed different Stylesheet files with assetic in a twig template of a Symfony2 project. The used stylesheet depends on the theme setting of the user.
我用过
{% stylesheets
'@CuteFlowCoreBundle/Resources/public/css/application.css'
'@CuteFlowCoreBundle/Resources/public/css/theme/'~app.session.get('cuteflow_theme')~'/application.css'
%}
<link rel="stylesheet" href="{{ asset_url }}" type="text/css" media="all" />
{% endstylesheets %}
但这会引发错误:
Unexpected token "operator" of value "~" in "CoreBundle::layout.html.twig"
我也尝试了以下方法.但这也无济于事.
I tried the following too. But this didn't help either.
{% set theme = '@CuteFlowCoreBundle/Resources/public/css/theme/'~app.session.get('cuteflow_theme')~'/application.css' %}
{% stylesheets
'@CuteFlowCoreBundle/Resources/public/css/application.css'
theme
%}
<link rel="stylesheet" href="{{ asset_url }}" type="text/css" media="all" />
{% endstylesheets %}
知道如何做到这一点吗?
Any ideas how this can be done?
推荐答案
答案很简单:你做不到.
The answer is simple : you cannot do it.
Assetic 将迭代您的模板并从 {% stylesheets %}
块生成每个文件.
Assetic will iterate your templates and generate every files from {% stylesheets %}
blocks.
如果您使用变量(例如会话),Assetic 无法猜测"所有可能的值.
If you use a variable (session for example), Assetic cannot "guess" all possible values.
你有两种可能性:
- 单独的 2 个 CSS 调用(1 个用于普通调用,1 个用于专用主题 CSS)-对我来说更有意义
- 为每个主题创建 1 个 CSS
单独的 2 个 CSS 调用
{% stylesheets "A.css" "B.css" %} ... {% endstylesheets %}
<link rel="stylesheet" href="{{ asset("css/" ~ theme ~ ".css") }}" />
为每个主题创建 1 个 CSS
如果您想为每个可用主题创建一个主题,为了简单起见,您必须手动进行:
If you want to create one theme for each available theme, for keeping it simple, you have to do it manually :
{% if theme == "XXX" %}
{%stylesheets "A.css" "XXX.css" %} ... {% endstylesheets %}
{% elseif theme == "YYY" %}
{%stylesheets "A.css" "YYY.css" %} ... {% endstylesheets %}
{% endif %}
这篇关于如何根据会话中的值使用 Assetic 嵌入样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!