我真的是 JavaScript 的新手,我无法找到关于这方面的一些教程。如果有,请告诉我阅读它们。
我想做的是将变量从我的 PHP Controller 传递到 .js 文件 - 我想填充 Highcharts 变量。
我知道我可以发送响应,但我还需要加载一个模板。
这是模板:
...
{% block body %}
<h1>Months</h1>
// This is the Chart:
<div id="container" style="width:100%; height:400px;"></div>
{%block javascript%}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="{{ asset('bundles/acmebudgettracker/js/month.js') }}"></script>
{%endblock%}
{% endblock %}
.js 文件名为 month.js
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Budget for months'
},
xAxis: {
categories: ['Spent', 'Saved']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
});
和 Controller :
public function monthsAction()
{
$this->setUser();
$month_repository = $this->setRepository('Month');
$month = new Month();
$form = $this->createForm(new MonthType(), $month);
$all_months = $month_repository->findByUser($this->user);
return $this->render('AcmeBudgetTrackerBundle:Months:months.html.twig', array(
'all_months' => $all_months,
'form' => $form->createView()
));
}
我想做的是将变量从 Controller 提供给 month.js,并且仍然能够显示模板。任何想法或教程如何实现这一目标?提前致谢!
最佳答案
您可以生成 javascript 作为 twig 模板:
MonthsController.php
public function scriptAction()
{
// some logic
return $this->render('AcmeDemoBundle:Months:script.js.twig', array(
'user_months' => $user_months
));
}
路由.yml
javascript_route:
path: /generated-scripts/month.{_format}
defaults: { _controller: AcmeDemoBundle:Article:script, _format: js }
requirements:
_format: js|json
script.js.twig
$(function () {
var options = {
chart: {
type: 'bar'
},
title: {
text: 'Budget for months'
},
xAxis: {
categories: ['Spent', 'Saved']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: []
};
{% for user in user_months %}
options.series.push({ name: '{{ user.name }}', data: [{{ user.months|join(',') }}] };);
{% endfor %}
$('#container').highcharts(options);
});
关于javascript - 将变量从 Symfony2 PHP 文件发送到 js 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17103900/