css - How to pass a Javascript variable to Twig in this particular example -


the following code in twig template , it's load css file or depending on theme selected user. works on simple html page when try take twig template of symfony application can't find way pass css route (with twig) javascript document.write function.

<script> var themesettings = (localstorage.getitem('themesettings')) ? json.parse(localstorage.getitem('themesettings')) :         {};         var themename = themesettings.themename || '';         if (themename)         {             document.write('<link rel="stylesheet" id="theme-style" href="css/app-' + themename + '.css">');         }         else         {             document.write('<link rel="stylesheet" id="theme-style" href="css/app.css">');         } 

in other words: want put in href of document.write function (in twig) this:

<link href="{{ asset('bundles/activos/css/app-red.css') }} "rel="stylesheet" > 

where "app-" invariable , word "red" variable depending on value of var themename

for i've try this:

<script>     var themesettings = (localstorage.getitem('themesettings')) ? json.parse(localstorage.getitem('themesettings')) :     {};     var themename = themesettings.themename || '';     if (themename)     {     document.write('<link rel="stylesheet" id="theme-style" href="{{  asset('bundles/activos/css/app-' ~ themename ~ '.css') }} ">');     }     else     {     document.write('<link rel="stylesheet" id="theme-style" href="{{  asset('bundles/activos/css/app.css') }} ">');     } </script> 

but doesn't work, gave me error:

variable "themename" not exist in ::base.html.twig @ line 1188

i guess it's because themename not twig variable javascript variable.

i think problem here can't pass javascript variable twig because javascript client-side , twig server-side. so, how can solve problem? maybe i'm going through wrong way, maybe using ajax can option, don't know how it.

to concat in javascript have use '+' operator

'~' operator twig concatenation

document.write('<link rel="stylesheet" id="theme-style" href="{{  asset('bundles/activos/css/app-' + themename + '.css') }} ">'); 

Comments