如何访问symfony2中另一个html.twig文件中的javascript变量?

时间:2014-09-15 15:15:52

标签: javascript html symfony variables twig

我想知道如何访问symfony2中另一个html.twig文件中的javascript变量。假设我们有两个html \ twig文件:file1.html.twig和file2.html.twig,它们的代码如下:

file1.html.twig的代码:

 <html>
    <head>
    <script>
    $(document).ready(function() {
      var calendar = $('#calendar').fullCalendar({
       //here is some code
      });
    });
    </script>
    </head>
    <body>
    </body>
    </html>

file2.html.twig的代码:

<html>
        <head>
        <script>
        function f1(){
            //here is the code that I need to access to the variable calendar of the file file1.html.twig
        }
        </script>
        </head>
        <body>
<form id="EventForm" action='{{path('ikproj_groupe_homepaeventsAdd',{id:idg})}}' method="POST" {{ form_enctype(form) }} onsubmit="f1();">
//here the body of the form
</form>
        </body>
        </html>

实际上,我想知道的是如何在文件file2.html.twig中访问file1.html.twig的变量“calendar”。所以我的问题是可以这样做??如果是的话,怎么样?

1 个答案:

答案 0 :(得分:2)

将您要共享的代码放在.js文件中:

// src/Acme/FooBundle/Resources/public/js/sharedCode.js

$(document).ready(function() {
    var calendar = $('#calendar').fullCalendar({
       //here is some code
    });
});

然后只需在任何地方包含脚本:

<html>
<head>
    ...
</head>
<body>
    ...

    {% javascripts '@AcmeFooBundle/Resources/public/js/sharedCode.js' %}
        <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
</body>
</html>