How to embed stylesheets with Assetic based on a value in the session
Asked Answered
R

1

6

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.

I used

{% 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 %}

But this throws an error:

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?

Reagent answered 21/7, 2011 at 15:27 Comment(1)
If you can't get it to work in twig, I'd try registering assets in code from your controller. It's not as pretty, but it should work.Conquer
U
10

The answer is simple : you cannot do it.

Assetic will iterate your templates and generate every files from {% stylesheets %} blocks.

If you use a variable (session for example), Assetic cannot "guess" all possible values.

You have 2 possibilities :

  • Separate 2 CSS calls (1 for common call, 1 for dedicated theme CSS) - makes more sense to me
  • Create 1 CSS per theme

Separate 2 CSS calls

{% stylesheets "A.css" "B.css" %} ... {% endstylesheets %}
<link rel="stylesheet" href="{{ asset("css/" ~ theme ~ ".css") }}" />

Create 1 CSS per theme

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 %}
Underprop answered 27/7, 2011 at 9:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.