以下代码在我的Twig
模板,它用于加载CSS
文件或其他文件,具体取决于用户选择的主题。这在一个简单的HTML
页面但是当我尝试将其带到Twig
我的模板Symfony
应用程序我找不到通过的方法CSS
路线(与Twig
)到Javascript
document.write
功能。
<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">');
}
换句话说:我想放入href
of the document.write
函数什么(在Twig
)会是这样的:
<link href="{{ asset('bundles/activos/css/app-red.css') }} "rel="stylesheet" >
其中“app-”是不变的,单词“red”是可变的,具体取决于 var 的值themeName
为此我尝试过这个:
<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>
但它不起作用,它给了我这个错误:
::base.html.twig 第 1188 行处不存在变量“themeName”
我想这是因为themeName
不是一个Twig
变量但是一个Javascript
多变的。
我认为这里的问题是我无法通过Javascript
变量为Twig
因为Javascript
is client-side
and Twig
is server-side
。
那么,我该如何解决这个问题呢?也许我正在经历错误的方式,也许使用Ajax
可以是一个选择,但我不知道该怎么做。