Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partials template in underscore (just like in handlebars)?

I have a backbone model like this

var PeopleModel = Backbone.Model.extend({
defaults: {              
    "people": [
          { "username": "alan", "firstName": "Alan", "lastName": "Johnson", "phone": "1111", "email": "[email protected]" },
          { "username": "allison", firstName: "Allison", "lastName": "House", "phone": "2222", "email": "[email protected]" },
          { "username": "ryan", "firstName": "Ryan", "lastName": "Carson", "phone": "3333", "email": "[email protected]" },
          { "username": "ed", "firstName": "Edward", "lastName": "Feild", "phone": "4444", "email": "[email protected]" },
          { "username": "phil", "firstName": "Philip", "lastName": "Doom", "phone": "5555", "email": "[email protected]" },
          { "username": "gerald", "firstName": "Gerald", "lastName": "Butler", "phone": "6666", "email": "[email protected]" }
    ],
    "company": {"name": "Random Corp."},
    "country": "England"
}

});

And below are my templates

<script id="people-template" type="text/x-handlebars-template">
{{#each people}}
  {{> person}}
{{/each}}
</script>

<script id="person-partial" type="text/x-handlebars-template">
 <div class="person">
    <h2>{{fullName}} </h2>
    <div class="phone">{{phone}}</div>
   <div class="email"><a href="mailto:{{email}}">{{email}}</a></div>    
 </div>

This is how I implemented partial using handlebars.js.

My questions

1.Do we have similar thing, I mean the partials incase of underscore.js template engine?

2.If so how do we implement partial in underscore.js template engine

like image 709
bhargav Avatar asked Jul 02 '12 09:07

bhargav


People also ask

What is partial in handlebars with examples?

In this article, we will discuss about Partials in Handlebars.js with examples. Handlebars allows code reuse using Partials. A Partial is a common template that can be included in another template. To create and register a partial, the method Handlebars.registerPartial () can be used as show below :

What is underscore JS template?

The Underscore.js template() method takes the latter approach, providing simple hooks for executing JavaScript in and around parts of your template's HTML. This low-level approach can lead to some strange looking template markup; but, it definitely provides for the most power and flexibility.

How do I reuse a template in handlebars?

Handlebars allows for template reuse through partials. Partials are normal Handlebars templates that may be called directly by other templates. In order to use a partial, it must be registered via Handlebars.registerPartial.

Why use handlebars for rendering templates?

This is nice because you can then write a utility function for rendering a template whether it be a full blown template or partial. Hope this helps anyone else who wants to use Handlebars like I do.


2 Answers

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:

<script id="people-template" type="text/x-handlebars-template">
    <% _(people).each(function(person) { %>
      <%= partial('person', person) %>
    <% }) %>
</script>

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.

like image 114
mu is too short Avatar answered Nov 05 '22 19:11

mu is too short


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.

like image 37
Brave Dave Avatar answered Nov 05 '22 19:11

Brave Dave