Partials template in underscore (just like in handlebars)?

前端 未结 3 1897
囚心锁ツ
囚心锁ツ 2021-01-02 05:03

I have a backbone model like this

var PeopleModel = Backbone.Model.extend({
defaults: {              
    \"people\": [
          { \"username\": \"alan\", \         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 05:28

    No, there is no native partial support in Underscore's templates. But, you can put pretty much any JavaScript you want inside <% ... %>; in particular, you can call your own functions so you can add something partial-ish without much difficulty. You could have a template like this:

    
    

    and then add a partial function to window:

    window.partial = function(which, data) {
        var tmpl = $('#' + which + '-partial').html();
        return _.template(tmpl)(data);
    };
    

    Demo: http://jsfiddle.net/ambiguous/HDuj5/9/

    That's not quite as slick and pretty as {{> ... }} in Handlebars but Underscore's templates are a very thin wrapper around JavaScript itself and that limits you somewhat. You can use namespaces to avoid putting things directly in window or you could use the {variable: ...} option to _.template and a wrapper to set up your standard helpers.

提交回复
热议问题