How to embed Assetic style sheets based on value in a session

I want to embed various stylesheets with assetic in the twig template of the Symfony2 project. The style sheet used depends on the user theme setting.

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 causes an error:

 Unexpected token "operator" of value "~" in "CoreBundle::layout.html.twig" 

I also tried the following. But that 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 to do this?

+6
source share
1 answer

The answer is simple: you cannot do this.

Assetic will iterate over your templates and generate all the files from the {% stylesheets %} blocks.

If you use a variable (such as a session), Assetic cannot β€œguess” all the possible values.

You have 2 options:

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

Split 2 CSS calls

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

Create 1 CSS for each theme

If you want to create one theme for each available theme, to simplify it you need to do it manually:

 {% if theme == "XXX" %} {%stylesheets "A.css" "XXX.css" %} ... {% endstylesheets %} {% elseif theme == "YYY" %} {%stylesheets "A.css" "YYY.css" %} ... {% endstylesheets %} {% endif %} 
+10
source

Source: https://habr.com/ru/post/893285/


All Articles