javascript - Partials template in underscore (just like in handlebars)? -
i have backbone model this
var peoplemodel = backbone.model.extend({ defaults: { "people": [ { "username": "alan", "firstname": "alan", "lastname": "johnson", "phone": "1111", "email": "alan@test.com" }, { "username": "allison", firstname: "allison", "lastname": "house", "phone": "2222", "email": "allison@test.com" }, { "username": "ryan", "firstname": "ryan", "lastname": "carson", "phone": "3333", "email": "ryan@test.com" }, { "username": "ed", "firstname": "edward", "lastname": "feild", "phone": "4444", "email": "ed@test.com" }, { "username": "phil", "firstname": "philip", "lastname": "doom", "phone": "5555", "email": "phil@test.com" }, { "username": "gerald", "firstname": "gerald", "lastname": "butler", "phone": "6666", "email": "gerald@test.com" } ], "company": {"name": "random corp."}, "country": "england" } });
and below 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 how implemented partial using handlebars.js.
my questions
1.do have similar thing, mean partials incase of underscore.js template engine?
2.if how implement partial in underscore.js template engine
no, there no native partial support in underscore's templates. but, can put pretty javascript want inside <% ... %>
; in particular, can call own functions can add partial-ish without difficulty. have template this:
<script id="people-template" type="text/x-handlebars-template"> <% _(people).each(function(person) { %> <%= partial('person', person) %> <% }) %> </script>
and add partial
function window
:
window.partial = function(which, data) { var tmpl = $('#' + + '-partial').html(); return _.template(tmpl)(data); };
demo: http://jsfiddle.net/ambiguous/hduj5/9/
that's not quite slick , pretty {{> ... }}
in handlebars underscore's templates thin wrapper around javascript , limits somewhat. can use namespaces avoid putting things directly in window
or use {variable: ...}
option _.template
, wrapper set standard helpers.
Comments
Post a Comment