使用 Twig 处理动态 Javascript 文件
我正在开发一种带有特定功能块的仪表板迷你网站.使用 symfony2,我有一个专用路由/instagram,它获取一个 html 片段,显示在我们场地拍摄的所有图像.
I'm working on a kind of dashboard mini site that has blocks with a certain functionality. Using symfony2 I have a dedicated route /instagram that gets an html fragment that shows all the images taken in our venue.
我想每 10 分钟刷新一次这个块,所以我需要在一个带有 setTimeout 的函数中运行以下 javascript,为清楚起见省略了.
I want to refresh this block every 10 minutes, so i need to run the following javascript, in a function with a setTimeout, omitted for clarity.
jQuery('.gallery').load("/instagram", function() {
jQuery('.gallery').cycle({
fx: 'fade'
});
});
此代码位于@KunstmaanDashboardBundle/Resources/public/js/instagram.js"中,我通过 Assetic 运行以进行连接和优化.
This code is in "@KunstmaanDashboardBundle/Resources/public/js/instagram.js" that i run through Assetic for concatenation and optimization.
{% javascripts
'@KunstmaanDashboardBundle/Resources/public/js/thirdparty/jquery-1.7.min.js'
'@KunstmaanDashboardBundle/Resources/public/js/thirdparty/jquery.cycle.lite.js'
'@KunstmaanDashboardBundle/Resources/public/js/*'
filter='closure'
%}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
这可行,但我觉得这不是最佳方法,因为我必须在 load() 函数中对路线进行硬编码.要解决此问题,我需要将 instagram.js 内容移动到 Twig 模板并将其更改为:
This works, but i don't feel like this is an optimal approach because i have to hardcode the route in the load() function. To fix this i need to move the instagram.js content to the Twig template and change it to:
jQuery('.gallery').load("{{ path('KunstmaanDashboardBundle_instagram') }}", function() {
jQuery('.gallery').cycle({
fx: 'fade'
});
});
但是这样我就失去了 Assetic 的优化和内容优势的分离.而我们的自定义代码最需要这种优化.
But this way i lose the optimization and separation from content benefits of Assetic. And our custom code is in the most need of this optimizing.
所以我的问题是,我如何将 Assetic Javascript(和 css)与 Twig 解析器结合起来,以便我可以将上面的代码放在 instagram.js 文件中并使其工作:)
So my question is, how can i combine Assetic Javascript (and css for that matter) with the Twig parser so i can put the code above in the instagram.js file and make it work :)
推荐答案
您目前无法使用 Assetic 处理 Twig 模板的输出,因为 Assetic 会静态转储资产以用于生产,而 Twig 模板是在运行时处理的.
You cannot currently process the output of Twig templates with Assetic because Assetic dumps the assets statically for production whereas the Twig templates are processed at runtime.
对于这个问题,您可以使用 FOSJsRoutingBundle 来公开路由并在客户端处理它,然后您的 JavaScript 可以使用 Assetic 进行处理.
For this issue you may be able to use the FOSJsRoutingBundle to expose the route and process it client side, then your JavaScript could be processed with Assetic.
相关文章