使用外部复合jQuery模板 [英] Using external composite jQuery Templates

查看:82
本文介绍了使用外部复合jQuery模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这两个博客文章的启发下,我想尝试jQuery模板

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?

外部模板:

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


更新:

有关Encosia的新博客文章解释了此问题和答案...


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/

推荐答案

这种简单的远程加载技术不适用于复合模板,因为要加载的字符串本身不是有效的模板.您可以通过更改点击处理程序来使其正常工作:

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

这篇关于使用外部复合jQuery模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆