4

在受到这 2 篇博文的启发后,我想尝试 jQuery 模板

好吧,这对我来说不太有效。如果我在页面本身上有模板代码,它可以正常工作,但远程加载对我不起作用。似乎正在检索模板。这里有什么问题?

外部模板:

<script id="contactsTemplate" type="text/x-jquery-tmpl">
  <table class="contacts">
    <thead><tr><td class="ui-helper-hidden">Id</td><td>Name</td><td>City</td><td>State</td></tr></thead>
    <tbody>
    {{each contact}}
        {{tmpl($value) '#contactTemplate'}}
    {{/each}}
    </tbody>
  </table>
</script>

<script id="contactTemplate" type="text/x-jquery-tmpl">
    <tr><td class="ui-helper-hidden">${id}</td><td>${name}</td><td>${city}</td><td>${state}</td></tr>
</script>

在我的页面上,我使用此代码来检索和加载模板:

var contacts = {
    contact: [
        { id: 1, name: "John Green", city: "Orange Beach", state: "AL" },
        { id: 2, name: "Sam Thompson", city: "Pensacola", state: "FL" },
        { id: 3, name: "Mary Stein", city: "Mobile", state: "AL" }
    ]
};

$("#ShowDataRemote").button().click(function() {
    $.get('templates/Contact.htm', function(template) {
        alert(template);
        $.tmpl(template, contacts).appendTo("body");
        alert("async done");
    });
});

更新:

Encosia 上的一篇新博客文章解释了这个问题和答案......

http://encosia.com/2010/12/02/jquery-templates-composite-rendering-and-remote-loading/

4

2 回答 2

3

这种简单的远程加载技术不适用于复合模板,因为您正在加载的字符串本身不是有效的模板。你可以通过改变你的点击处理程序来让它工作,如下所示:

$("#ShowDataRemote").button().click(function() {
  $.get('templates/Contact.htm', function(template) {
    // Inject the template script blocks into the page.
    $('body').append(template);

    // Use those templates to render the data.
    $('#contactsTemplate').tmpl(contacts).appendTo("body");
  });
});
于 2010-11-30T16:26:07.150 回答
0

您可以将模板字符串编译为“命名模板”,如以下参考:https ://stackoverflow.com/a/4366280/1274343

于 2012-10-16T13:45:55.907 回答