我目前正在对我的工作流程进行现代化改造,尤其是在前端部分,并开始使用 require.js , qunit , backbone.js , underscore.js等,在我上一个不需要后端的项目中。
来自 Symfony2,我习惯于通常在 Twig 中编写我的模板,并让 Assetic 制作所有必要的魔法,如 js/css 缩小、 Assets 等。Research shows Assetic 目前无法按照 require.js 需要的方式提供 javascript 文件。
现在我真的很喜欢 RequireJS 背后的想法,Asynchronous Module Definition (AMD) 并且想知道如何在 Symfony2 项目中从它的强大功能中获益。恕我直言,最明智的方法是减少 Symfony2 项目以简单地提供必要的数据,例如通过提供 RESTful 接口(interface)。这将进一步导致可以更独立地开发和测试的完全解耦的前端 <> 后端。
我的问题是:我不会失去 Symfony2 给我的一些好处,比如完整的表单处理(CSRF 保护、验证等)和安全性吗?有没有人已经这样做并且能够分享一些见解?是否有一些缺点/陷阱需要寻找?而且……值得吗? ;-)
最佳答案
在我的主 Twig 模板中,我定义了(例如 {% block js %})这样的 javascript 部分
<script type="text/javascript">
var config = {
getCoreBundleName: function() {
return 'openframeworkcore';
},
getPath: function(bundleName, filePath) {
return bundleName + '/components/' + filePath;
},
getCorePath: function(filePath) {
return this.getPath(this.getCoreBundleName(), filePath);
}
};
require.config({
baseUrl: '{{ app.request.getBasePath() }}/bundles/',
paths: {
core: 'openframeworkcore/core/js/core',
bootstrap: config.getCorePath('bootstrap/dist/js/bootstrap')
},
shim: {
bootstrap: {
deps: ['jquery']
},
fancybox: {
deps: ['jquery', 'jquery-mousewheel']
},
angular: {
exports: 'angular'
},
restangular: {
deps: ['underscore', 'angular']
},
'jquery-ui': {
deps: ['jquery']
}
}
});
// loads the core.js
require(['core']);
</script>
在我的情况下,我使用了 restangular。一个使用 rest 方法扩展 angularjs 的框架。 但它只是提供了一些辅助方法来进行restful通信。
另一方面,restangular 与 Symfony2 完美结合
/**
* @Route("/create")
* @Method({"GET"})
* @Template()
*/
public function createAction(Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$form = $this->createForm(new BoardType());
return array(
'form' => $form->createView()
);
}
我已经将 requirejs 与 Symfony2 相结合 如需进一步的问题,请随时问我。
干杯
关于javascript - 在 Symfony2 项目中可以使用 require.js 和异步模块定义 (AMD) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19340169/