使用 Javascript 访问通过 Twig 传递的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13928729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:08:36  来源:igfitidea点击:

Use Javascript to access a variable passed through Twig

phpjavascriptsymfonytwig

提问by clifford.duke

I have a controller that passes an array to a twig template, which I want to use in a script written on that page. How would I go about doing that?

我有一个将数组传递给树枝模板的控制器,我想在该页面上编写的脚本中使用该模板。我该怎么做?

I've tried this in my .twig template:

我在我的 .twig 模板中试过这个:

<script>
    $(document).ready(function(){
        var test = {{ testArray }};
});
</script>

but that only works if it's a string.

但这仅在它是字符串时才有效。

回答by Supericy

You might have to json_encodethe array, try this:

你可能需要json_encode数组,试试这个:

<script>
    $(document).ready(function(){
        var test = {{ testArray|json_encode|raw }};
    });
</script>

回答by user3189566

First, send the data json encoded from controller and

首先,发送从控制器编码的数据json和

then in javascript,

然后在javascript中,

var context= JSON.parse('{{ YourArrayFromController|raw}}');

回答by shades3002

I do it this way:

我这样做:

Return of the controller test.data then

然后返回控制器 test.data

$test = array('data' => array('one','two'))

Twig:

枝条:

<div id="test" data-is-test="{{ test.data|json_encode }}"></div>

Js:

JS:

$(document).ready(function() {
    var test = $('#test').data("isTest");
    console.log(test);
});

Output:

输出:

 ["one", "two"]

documentation here

文档在这里

回答by Mourad MAMASSI

In My Controller I Install SerializerBundle

在我的控制器中,我安装了 SerializerBundle

$serializer = $this->get('serializer');
        $countries = $this->getDoctrine()->getRepository("QSCORBundle:CountryMaps")->findAll();
        $jsonCountries = $serializer->serialize($countries, 'json');
 return $this->render('QSCORBundle:Default:index.html.twig',array("countries"=> $jsonCountries));

And In My File Twig

在我的文件树枝中

<script type="text/javascript" >
 var obj = {{ countries|json_encode|raw }};
 var myObject = eval('(' + obj + ')');

 console.log(myObject[0]['capital_latitude'] + " " + myObject[0]['capital_longitude']);//for the First Element
</script>