如何在不提供任何现有容器的情况下将jQuery.loadTemplate转换为新元素?

时间:2014-04-30 02:41:52

标签: jquery

$("#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元素,如何直接创建新元素并从模板中填充?

2 个答案:

答案 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'
});

被修改

我不确定你想做什么!!!我无法想象你可能想要加载模板以外的任何其他事情,如下所示:

  1. 您可能希望在自己的页面中显示内容,在这种情况下,您可以像使用代码一样将元素用作容器
  2. 您可能不想在页面中显示内容,这种情况下您可以使用我的第二个代码段。
  3. 无论如何,我没有猜测力量!!您可以定义以下函数,并使用它来获取内容,并使用它执行任何操作:

     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 });