以下代码加载模板。
tpl = {
// Hash of preloaded templates for the app
templates: {},
// Recursively pre-load all the templates for the app.
// This implementation should be changed in a production environment. All the template files should be
// concatenated in a single file.
loadTemplates: function(names, callback) {
var that = this;
var loadTemplate = function(index) {
var name = names[index];
console.log('Loading template: ' + name);
$.get('tpl/' + name + '.html', function(data) {
that.templates[name] = data;
index++;
if (index < names.length) {
loadTemplate(index);
} else {
callback();
}
});
}
loadTemplate(0);
},
// Get template by name from hash of preloaded templates
get: function(name) {
return this.templates[name];
}
};
你可以加载像
这样的模板tpl.loadTemplates(['header', 'wine-details', 'wine-list-item'], function() {
});
但是这里的模板是在单独的html文件中定义的。
是否可以在一个html文件中定义所有模板,然后将它们一起加载。 我需要编写某种解析器吗?原因是我的主页我有40个模板,我不想创建40个Html模板页面,而是我可以将它们保存在一个单独的html页面中,而不是将它们全部加载在一起。
这可能吗?
答案 0 :(得分:0)
是的,你不需要像这样做。
请检查:https://github.com/requirejs/text
define([
'some/module',
'text!some/module.html',
'text!some/module.css'
], function (SomeModule, HtmlFile, CssFile) {
'use strict';
// ....
}
这可以加载文本资源。当您准备部署应用程序时,可以使用r.js将所有js文件和模板编译为单个缩小文件。您可以通过命令行或grunt或gulp任务执行此操作。
有许多模板库可以找到requirejs插件(通常扩展到该文本插件^^)。例如,这个用于Handlebars https://github.com/jfparadis/requirejs-handlebars或者这个用于下划线https://github.com/jfparadis/requirejs-tpl。只需谷歌搜索“requirejs«模板引擎名称»”。
如果您想在一个html文件中包含多个模板,则需要一种方法来分隔它们。最好的方法是使用新的template标记。
答案 1 :(得分:0)
您可以使用ID在不同的容器下定义模板单个文件。以你在这里加载的方式加载单个html,用模板html创建一个jquery节点,运行子读取id属性并保存每个保存为that.templates[id_you_read] = child.html();
的子项的html
但这不是正确的做事方式。像在prev答案中一样使用requirejs和text插件。