以下代码位于我的 Twig
模板中,用于加载 CSS
文件或其他文件,具体取决于用户选择的主题。这在简单的 HTML
页面上完美运行,但是当我尝试将其带到我的 Symfony
应用程序的 Twig
模板时,我找不到将 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">');
}
换句话说:我想在 document.write
函数的 href
中放入什么(在 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>
但是它不起作用,它给了我这个错误:
Variable "themeName" does not exist in ::base.html.twig at line 1188
我猜这是因为 themeName
不是一个 Twig
变量,而是一个 Javascript
变量。
我认为这里的问题是我无法将 Javascript
变量传递给 Twig
因为 Javascript
是 client- side
和 Twig
是服务器端
。
那么,我该如何解决这个问题呢?也许我走错了路,也许使用Ajax
可以是一个选择,但我不知道该怎么做。
最佳答案
要在 JavaScript 中连接,您必须使用“+
”运算符
'~
' 运算符用于 Twig 连接
document.write('<link rel="stylesheet" id="theme-style" href="{{ asset('bundles/activos/css/app-' + themeName + '.css') }} ">');
关于javascript - 在此特定示例中如何将 Javascript 变量传递给 Twig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38833005/