首页 > Backbone如何调用外部Handlebars模板文件~

Backbone如何调用外部Handlebars模板文件~

因为我现在是直接把Handlebars写在HTML页面中的,想问一下,如何将Handlebars模板文件做为一单独的文件引用使用呢?

Handlebars

<script id="template" type="text/x-handlebars-template">
    {{#each this}}
    <h3>{{ title }}</h3>
    <div class="sub">
        {{#each sub}}
            <dl class="items">
                <dt>{{ title }}</dt>
                {{#each subtitle}}
                    <dd>
                        <a href="{{ url }}">{{ title }}</a>
                    </dd>
                {{/each}}
            </dl>
        {{/each}}
    </div>
    {{/each}}
</script>

HTML:



<div class="nav" id="nav"></div> <script> var NavView = Backbone.View.extend({ template: Handlebars.compile( $('#template').html()), initialize: function() { this.render(); }, render: function() { var _t = this; $.getJSON('config/menu.json').done(function(data) { _t.$el.html(_t.template(data)); }); } }); var AppRouter = Backbone.Router.extend({ routes: { '': 'navRoute', 'nav': 'navRoute' }, navRoute: function() { var homeView = new NavView(); $('#nav').html(homeView.el); } }); var appRouter = new AppRouter(); Backbone.history.start(); </script>

我们用的是requireJS来管理这些文件。require text可以将文件以文本的形式加载进来。

在之前的一个项目里https://github.com/phodal/moqi.mobi是这样用的,我们之前用的是Mustache,但是都是一样的:

define([
    'jquery',
    'underscore',
    'mustache',
    'text!/templates/basic.html'
],function($, _, Mustache, basicTemplate ){
    var BasicView = Backbone.View.extend ({
        el: $("#basic"),

        initialize: function(){

        },
        render: function(){
            this.$el.html(Mustache.to_html(basicTemplate, {
                data:"data"
            }));

        }
    });

    return BasicView;
});

以上面的代码为例,我们将mustache的模板,即/templates/basic.html以文本的形式加载进来,然后to_html

【热门文章】
【热门文章】