The following code is for me to load on the page a CSS
or another depending on the chosen theme. This code works perfectly on page HTML
pure, but when I try to take my application Symfony
not found a way to pass the JS
%% route CSS
with Twig
.
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, I want the href
of the function document.write
to be loaded (for example) so with Twig
this would be:
<link href="{{ asset('bundles/activos/css/app-red.css') }} "rel="stylesheet" >
Where app-
is fixed and what varies is the word red
according to the value of variable themeName
For this I have tried the following but it does not work in this way:
<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>
This throws me this error:
Variable "themeName" does not exist in :: base.html.twig at line 1188
Then I tried to do this:
<script>
var themeSettings = (localStorage.getItem('themeSettings')) ? JSON.parse(localStorage.getItem('themeSettings')) :
{};
var themeName = themeSettings.themeName || '';
if (themeName)
{
var cadenacss = "asset('bundles/activos/css/app-')" ~ themeName ~ '.css">';
{% set cadena=cadenacss %}
document.write('<link rel="stylesheet" id="theme-style" href="{{ cadena }}">');
}
else
{
document.write('<link rel="stylesheet" id="theme-style" href="{{ asset('bundles/activos/css/app.css') }} ">');
}
</script>
And it does not work either, it shows me the following error:
Variable "stringcss" does not exist in :: base.html.twig at line 1189
I can not find a way to do this by passing the variable from JS to Twig. First I would like to know if there is any way to pass variables from JS to Twig, but if it can not be done, then I would like to know some other way that I can resolve this.