我正在为我的项目添加一个Highcharts。我想从数据库值中填充Javascript数组..
{% extends '::base.html.twig' %}
{% block stylesheets %}
{{ parent() }}
{% endblock %}
{% block body -%}
<div class="page-header">
Supporters
</div>
<div id="container" style="min-width: 300px; height: 400px; margin: 0 auto"></div>
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'World\'s largest cities per 2014'
},
subtitle: {
text: 'Source: <a href="http://en.wikipedia.org/wiki/List_of_cities_proper_by_population">Wikipedia</a>'
},
xAxis: {
type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Population (millions)'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: 'Population in 2008: <b>{point.y:.1f} millions</b>'
},
series: [{
name: 'Population',
/*data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Instanbul', 14.2],
['Karachi', 14.0],
['Mumbai', 12.5],
['Moscow', 12.1],
['São Paulo', 11.8],
['Beijing', 11.7],
['Guangzhou', 11.1],
['Delhi', 11.1],
['Shenzhen', 10.5],
['Seoul', 10.4],
['Jakarta', 10.0],
['Kinshasa', 9.3],
['Tianjin', 9.3],
['Tokyo', 9.0],
['Cairo', 8.9],
['Dhaka', 8.9],
['Mexico City', 8.9],
['Lima', 8.9]
],*/
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y:.1f}', // one decimal
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
});
</script>
{% endblock %}
我想从数据库中的实际值替换那些虚拟数据。我创建了一个方法,它将调用Doctrine并检索thos记录。到目前为止,我可以使用Symfony的转储工具成功检索这些数据。
$em = $this->getDoctrine()->getManager();
$province = $em->getRepository('DuterteBundle:Grps')->createQueryBuilder('g')
// ->join('p.region', 'r')
// ->where('r.id =:x')
// ->setParameter('x', 1)
->orderBy('g.name', 'ASC')
->getQuery()
->getResult();
// $dat = $this->container->get('duterte.twig.province_voters_extension');
$datas = array();//initialise array
foreach ($province as $r) {
// $datas[] = array($r->getName(),(int)$dat->a($r->getId()),$r->getName());
$datas[] = array($r->getName(),123);
}
$data = $datas;
echo '<pre>';
\Doctrine\Common\Util\Debug::dump($data);
echo '</pre>';
return $this->render('GraphBundle:Default:group.html.twig', array(
'data' => $data
));
变量数据包含我想在Javascript数据变量中填充的实际数据。如何实现这一点?我试着用这个
<script>
...
data= <?php $data ?>
/*data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Instanbul', 14.2],
['Karachi', 14.0],
['Mumbai', 12.5],
*/
</script>
在Twig环境中不起作用
答案 0 :(得分:1)
试试{{ data|json_encode|raw }}
。默认情况下,Twig将转义HTML的任何内容,|raw
过滤器会阻止该内容。
此外,如果您遇到json_encode
调用正在创建JavaScript对象{}
而不是数组[]
的问题,请致电array_merge
将数据传递给Twig之前的数据:
$data = array_merge($data);
这将重新键入数组以使用数字索引,并在使用json_encode
时正确转换为JavaScript数组。