【问题标题】:Loading underscore.js templates from a separate file从单独的文件加载 underscore.js 模板
【发布时间】:2012-01-25 07:41:27
【问题描述】:
我目前在项目中使用 underscore.js 进行模板化,模板存储在具有文本/模板类型的脚本标签中,并由 id 加载。我想知道是否可以继续使用相同的系统,但将模板移到单独的文件中?
我能想到的唯一方法是在单独的文件中将模板声明为全局变量,但这看起来很难看。
注意:我不想在部署时使用 Jammit 或其他构建系统将所有内容混合到一个文件中,想知道是否有其他解决方案。
【问题讨论】:
标签:
javascript
underscore.js
templating
【解决方案1】:
我个人使用 RequireJS 将我的模板加载到模块中,但如果您正在寻找其他东西,您可以使用 Ajax。
只要您的模板位于同一个域中,您就可以通过 ajax 获取它们
要求。如果使用我的小部件的人未使用 AMD 兼容库,我将返回以下代码:
$.ajax({
url: root.WIDGET.BaseUrl + 'templates/widget.html',
asynx: false, // synchonous call in case code tries to use template before it's loaded
success: function (response) {
widgetTemplate = response;
}
});
这假设你也在使用 jQuery,但如果你使用其他东西,原理是一样的。