Partials template in underscore (just like in handlebars)?

前端 未结 3 1894
囚心锁ツ
囚心锁ツ 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:23

    Or to avoid using global scope you can mix in global template helpers like so:

    (function() {
        var originalUnderscoreTemplateFunction = _.template;
        var templateHelpers = {};
    
        _.mixin({
            addTemplateHelpers : function( newHelpers ) {
                _.extend( templateHelpers, newHelpers );
            },
    
            template : function(text, data, settings) {
                // replace the built in _.template function with one that supports the addTemplateHelpers
                // function above. Basically the combo of the addTemplateHelpers function and this new
                // template function allows us to mix in global "helpers" to the data objects passed
                // to all our templates when they render. This replacement template function just wraps
                // the original _.template function, so it sould be pretty break-resistent moving forward.
    
                if( data )
                {
                    // if data is supplied, the original _.template function just returns the raw value of the
                    // render function (the final rentered html/text). So in this case we just extend
                    // the data param with our templateHelpers and return raw value as well.
    
                    _.defaults( data, templateHelpers ); // extend data with our helper functions
                    return originalUnderscoreTemplateFunction.apply( this, arguments ); // pass the buck to the original _.template function
                }
    
                var template = originalUnderscoreTemplateFunction.apply( this, arguments );
    
                var wrappedTemplate = function( data ) {
                    _.defaults( data, templateHelpers );
                    return template.apply( this, arguments );
                };
    
                return wrappedTemplate;
            }
        }
    }
    

    Then call

    _.addTemplateHelpers( {
        partial : function() {
            return _.template(
                $('#' + which + '-partial').html(),
                data
            );
        }
    } );
    

    Here is a link to the underscore mixin on github.

提交回复
热议问题