简体   繁体   English

javascript中找不到树枝变量

[英]twig variable not found in javascript

I'm trying to pass a twig array variable to javascript, but for some reason it keeps stating that the variable does not exist. 我正在尝试将细枝数组变量传递给javascript,但是由于某种原因,它一直在声明该变量不存在。

My twig: 我的树枝:

{% set clients = [] %}
{% for work in works %}

    {% set clients = clients|merge([ work.name ]) %}

{% endfor %}

{% set client_array = clients|json_encode|raw  %}

When I try and call client array with {{client_array}} I have no trouble whatsoever, it returns the correct array. 当我尝试使用{{client_array}}调用客户端数组时,我没有遇到任何麻烦,它将返回正确的数组。

However my problem is when I try to define a javascript variable below in a javascript block on the page to be equal to client_array. 但是我的问题是,当我尝试在页面上的javascript块下面定义一个javascript变量,使其等于client_array时。

<script>
var clients = '{{ client_array }}';
...
 </script>

I keep getting 我不断

Variable "client_array" does not exist. 变量“ client_array”不存在。

I feel there's some dumb syntax error I'm making here. 我觉得我在这里犯了一些愚蠢的语法错误。 Can anyone see the problem? 谁能看到这个问题?

ok, so I took a different approach to this and chose to set the variable in the controller and that worked 好的,所以我采取了另一种方法,选择在控制器中设置变量

    $clients = [];
    foreach ($works as $work) {
        $client = $work['name'];
        array_push($clients, $client);
    }

While comparing the output side by side, they were identical, so my conclusion is that it appears that twig "set" variables don't seem to be recognized outside the block. 并排比较输出时,它们是相同的,因此我的结论是,似乎在树枝外似乎看不到树枝“设置”变量。 (don't quote me on this) (不要在此引用我)

Try Passing Information from Twig to JavaScript 尝试将信息从Twig传递到JavaScript

In controller create variable: 在控制器中创建变量:

public function index(Request $request) {

    /* ... */
    $clients = array(array("id" => 1, "name" => "test1"), array("id" => 2, "name" => "test2"));
    $names = array_map(function ($ar) {
        return $ar['name'];
    }, $clients);
    $twigparms = array("clients" => $names);
    return $this->render("YourTemplate/index.html.twig", $twigparms);
}

in Twig use it 在树枝上使用它

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <title>Page Title</title>
    <body>

        <div class="clients" id="clients" data-names="{{ clients|json_encode|e('html_attr') }}"></div>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                var clientstmp = document.querySelector('.clients');
                var clients = clientstmp.dataset.names;
                console.log(clients);
            });
        </script>

    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM