你好,伙计们,我正试图将数组传递给js文件,但我有以下错误:
在模板的呈现过程中引发异常(“注意:数组到字符串的转换”)。
这就是我想要的:data: ['2017/7','2017/8']
所以我这样做(用树枝):data: '{{ user_month_month }}'
当我选择user_month_month时,这就是我得到的:
array(2) { [0]=> string(6) "2018-7" [1]=> string(6) "2018-8" }
所以我认为我在js部分中说得不好,我该怎么做?
如果你想要那里有我的控制器:
public function GraphicShow()
{
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository('AppBundle:User')->countUsers();
$not_logged = $em->getRepository('AppBundle:User')->countNotActiveUsers();
$logged = $em->getRepository('AppBundle:User')->countActiveUsers();
$user_month_months = $em->getRepository('AppBundle:Profile')->countByMonthMonth();
$user_month_totals = $em->getRepository('AppBundle:Profile')->countByMonthTotal();
$array_totals = array();
$array_months = array();
foreach($user_month_totals as $user_month_total) {
$array_totals[] = intval($user_month_total["total"]);
}
foreach ($user_month_months as $user_month_month) {
$array_months[] = $user_month_month["month"];
}
$not_logged_result = $not_logged["number"] / $users["number"] * 100;
$logged_result = $logged["number"] / $users["number"] * 100;
var_dump($array_months);
die();
return $this->render('admin/user/pie_stats.html.twig', array(
'user_month_month' => $array_months,
'user_month_total' => $array_totals,
'user_not_logged' => $not_logged_result,
'user_logged' => $logged_result,
'users' => $users,
'loggedAs' => $this->getUser(),
'alert' => 0,
));
}ps / edit :日期是图形的日期,它看起来如下:

希望我能解释得很好,给所有想要回答的人:p
使用DarkBee方法,我得到了以下内容:

发布于 2018-08-03 08:57:35
将数组从twig传递到javascript的最快方法是将数组转换为JSON,twig有一个内置过滤器编码,编码:
data: {{ user_month_month | json_encode | raw }}发布于 2018-08-03 09:12:58
symfony推荐的将信息从树枝传递到JavaScript的方法是将信息存储在数据属性中,然后在javascript中读取它们。这里的文件。
在您有一个数组的情况下,您应该使用它来按预期工作:
<div id="your-div" data-yourArray="{{ yourArray|json_encode|e('html_attr') }}">然后使用JSON.parse在javascript中反序列化数组。
DarkBee的答案不包括使用转义过滤器,这就是为什么它不能像预期的那样工作。
在您的javascript代码中:
var yourDiv = document.getElementById('your-div');
var yourArray = JSON.parse(yourDiv.dataset.yourArray); 发布于 2018-08-03 09:03:15
<input type="text" id="txt"> <!-- // 2017/7 2017/8 -->
<script>
date = '{{ user_month_month[0] ~ ' ' ~ user_month_month[1] }}';
alert(date); // 2017/7 2017/8
txt = document.getElementById('txt');
txt.value = "{{ user_month_month[0] ~ ' ' ~ user_month_month[1] }}";
</script>https://stackoverflow.com/questions/51668833
复制相似问题