Using external composite jQuery Templates

我是研究僧i 提交于 2019-12-05 02:11:21

问题


I wanted to try out jQuery Templates after being inspired by these 2 blog postings

  • http://encosia.com/2010/11/10/composition-with-jquery-templates-why-and-how/
  • http://encosia.com/2010/10/05/using-external-templates-with-jquery-templates/

Well, it's not quite working for me. If I have the template code on the page itself it works fine, but loading remotely isn't working for me. It appears the template is being retrieved ok. what is wrong here?

External template:

<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>

On my page I'm using this code to retrieve and load the template:

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

Update:

A new blog post on Encosia explains this question and answer...

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


回答1:


That simple remote loading technique won't work with composite templates, since the string you're loading isn't a valid template itself. You can get it working by changing your click handler like this:

$("#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");
  });
});



回答2:


You can compile template string as a "named template", like this reference: https://stackoverflow.com/a/4366280/1274343



来源:https://stackoverflow.com/questions/4315679/using-external-composite-jquery-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!