如何加载外部html模板?

时间:2014-01-25 12:23:44

标签: javascript jquery handlebars.js

给定HTML代码,例如:

<!-- 2. Anchor -->
<div id="anchor">This div is the <b>#anchor</b>.</div>

<!-- 3. Template -->
<script id="tpl" type="text/template">
    {{#people}}
        <div><img src="{{photo}}"><b><a href="{{twitter}}">{{family}} {{name}}</a></b> — {{title}}, {{place}} : {{introduction}}.</div>
    {{/people}}
</script>

给定JS / Handlebars ,例如:

 <!--4. Handlebars.js slingshot -->
 //4a.function creation
 var slingshot = function (url, tplId, anchor) {
   $.getJSON(url, function(data) {
       var template = $(tplId).html();
       var stone = Handlebars.compile(template)(data);
       $(anchor).append(stone);
   });
 }

 slingshot('data.json', '#tpl', '#anchor'); // since url = 'data.json' , we can use both notations.

如何将我的3. Template(#tpl)外部化为正确的.txt文本文件(或其他扩展程序)?如何加载?所以我可以将相同的模板用于各种.html网页。

完整代码:http://bl.ocks.org/hugolpz/8075193 / http://bl.ocks.org/hugolpz/raw/8075193/

2 个答案:

答案 0 :(得分:1)

将以下模板内容放入名为test.handlebars

的文件中
{{#people}}
    <div><img src="{{photo}}">
       <b>
         <a href="{{twitter}}">{{family}} {{name}}</a>
       </b> — {{title}},      
            {{place}} : {{introduction}}.
    </div>
{{/people}}

编写一个将使用以下模板的函数

function getTemplate(name) {

if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
  $.ajax({
   url : name + ".handlebars",
   success : function(data) {
       if (Handlebars.templates === undefined) {
           Handlebars.templates = {};
       }
       Handlebars.templates[name] = Handlebars.compile(data);
   },
   async : false
 });
}
return Handlebars.templates[name];
 }

在主程序中,您可以编写以下语句,将模板内容插入到div =“anchor”的div中,如下所示

var Template = getTemplate("test")
this.$("#anchor).append(Template(data));

其中data是json文件或某个db查询输出的内容,它将为您提供以json格式表示以下属性的值

人,推特,姓名,家庭,照片,标题,地点,介绍

答案 1 :(得分:1)

我假设你have already compiled your template。所以你可以使用我在Bootstrapping Multiple Instances of an HandlebarsJS Template Into a Page中描述的技术。

Hook and libs

将其放在index.html

<div class="hook" data-json="data/whatever.json"></div>

和JavaScript库

<!-- Helper to inject data-set in templates instance -->
<script src="scripts/template-loader.js"></script>
<!-- Get the (compiled) template -->
<script src="scripts/myTemplate.hbs.js"></script>

template-loader.js helper

$(function(){
    'use strict';
    var compiledTemplate = myApp.Templates['app/templates/myTemplate.hbs'];

    $('.hook').each(function(i, h){              # h = current hook
        var url = $(h).data('json');             # data-set's url
        $.getJSON(url).then(function (json) {    # fetch data-set
            var tpl = compiledTemplate( json );  # inject data into template
            $(h).html(tpl);                      # inflate template in page
        });
    });
});

请阅读完整的文章了解更多详情。