Javascript 如何加载外部html模板?

Javascript 如何加载外部html模板?,javascript,jquery,handlebars.js,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}}">

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

这个部门是主播。
{{{人}
-{{title},{{place}:{{{introduction}。
{{/人}
给定的JS/把手如:

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

//4a.功能创建
var slingshot=函数(url、tplId、锚定){
$.getJSON(url、函数(数据){
var template=$(tplId.html();
var stone=把手。编译(模板)(数据);
$(锚)。附加(石头);
});
}
slingshot('data.json','#tpl','#anchor');//由于url='data.json',我们可以同时使用这两种符号。
如何将my
3外部化。模板(#tpl)转换为正确的.txt文本文件(或其他扩展名)?如何重新加载?这样我就可以在不同的.html网页中使用相同的模板


完整代码:///p>将以下模板内容放入名为test.handlebar的文件中

{{#people}}
    <div><img src="{{photo}}">
       <b>
         <a href="{{twitter}}">{{family}} {{name}}</a>
       </b> — {{title}},      
            {{place}} : {{introduction}}.
    </div>
{{/people}}
在主程序中,您可以编写下面的语句,用id=“anchor”将模板内容插入div,如下所示

var Template = getTemplate("test")
this.$("#anchor).append(Template(data));
其中,数据是json文件的内容或某个db查询输出,它将以json格式为您提供以下属性的值

人,推特,姓名,家庭,照片,头衔,地点,介绍我假设你。因此,您可以使用我在中描述的技术

钩子和libs 将其放入您的
index.html

<div class="hook" data-json="data/whatever.json"></div>
请阅读完整的文章以了解更多细节

<div class="hook" data-json="data/whatever.json"></div>
<!-- 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>
$(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
        });
    });
});