$("#template-container").loadTemplate($("#template"),
{
author: 'Joe Bloggs',
date: '25th May 2013',
authorPicture: 'Authors/JoeBloggs.jpg',
post: 'This is the contents of my post'
});
在此示例中需要现有的#template-container元素,如何直接创建新元素并从模板中填充?
答案 0 :(得分:3)
您可以使用与容器相同的内容。例如:
您可以使用将模板加载到新创建的div元素中,并将其附加到其他元素。
$('<div/>').loadTemplate($("#template"), {
author: 'Joe Bloggs',
date: '25th May 2013',
authorPicture: 'Authors/JoeBloggs.jpg',
post: 'This is the contents of my post'
}).appendTo("#someohter_element");
或者如果您引用任何动态创建的元素,如
var el = $('<div/>');
然后你也可以打电话
el.loadTemplate($("#template"), {
author: 'Joe Bloggs',
date: '25th May 2013',
authorPicture: 'Authors/JoeBloggs.jpg',
post: 'This is the contents of my post'
});
我不确定你想做什么!!!我无法想象你可能想要加载模板以外的任何其他事情,如下所示:
无论如何,我没有猜测力量!!您可以定义以下函数,并使用它来获取内容,并使用它执行任何操作:
function loadTemplate(template, data, options){
return $('<div/>').loadTemplate(template, data, options).html();
}
然后使用它:
var markup = loadTemplate("#template",
{
author: 'Joe Bloggs',
date: '25th May 2013',
authorPicture: 'Authors/JoeBloggs.jpg',
post: 'This is the contents of my post'
});
markup
变量将在渲染模板后包含html
快乐的编码!
答案 1 :(得分:0)
如果您尝试在容器上附加数据,则可以使用{append: true}
选项,例如:
$("#template-container").loadTemplate($("#template"),
{
author: 'Joe Bloggs',
date: '25th May 2013',
authorPicture: 'Authors/JoeBloggs.jpg',
post: 'This is the contents of my post'
}, {
append: true
});