将变量从Symfony2 PHP文件发送到js文件

时间:2013-06-14 08:07:06

标签: javascript symfony highcharts

我是JavaScript的新手,我对这方面的一些教程不太好。如果有,请告诉我阅读。

我想要做的是将变量从PHP控制器传递到.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]
    }]
});

});

控制器:

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()
    ));
}

我想要做的是将变量从控制器提供给month.js,并且仍然能够显示模板。任何想法或教程如何实现这一目标?提前谢谢!

2 个答案:

答案 0 :(得分:14)

您可以生成javascript为twig模板:

MonthsController.php

public function scriptAction()
{
    // some logic
    return $this->render('AcmeDemoBundle:Months:script.js.twig', array(
        'user_months' => $user_months
    ));
}

的routing.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);
});​

答案 1 :(得分:8)

快速&amp; “脏”答案:使用应答器在TWIG文件中设置变量,并在JS文件中使用这些变量。

<script>
    var foo = {{ bar }};
</script>