javascript - 在此特定示例中如何将 Javascript 变量传递给 Twig

标签 javascript css ajax symfony twig

以下代码位于我的 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 因为 Javascriptclient- sideTwig服务器端。 那么,我该如何解决这个问题呢?也许我走错了路,也许使用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/

相关文章:

javascript - 翻译/本地化/国际化静态页面和单页应用程序

javascript - 谷歌地图 : Cannot read property 'geometry' of undefined

html - 使用 <div> 在 html 中获取所需的布局

php - Ajax 将对象数组返回给 jquery 和 php

jquery - jquery中变量的问题

javascript - 在 gridview 中弹出更多详细信息?

javascript - 暂时禁用 node.js 垃圾收集

html - 将类选择器与 ID 组合

jquery - 如何在 fancytree jquery 中获取树元数据

javascript - 从 xhttp.open ("Get"动态填充下拉列表;回复