Friday 15 March 2013

javascript - Backbone Inline HTML Templates versus External Templating -



javascript - Backbone Inline HTML Templates versus External Templating -

my backbone app has inline html templates follows:

<body> <div id="container"> <header></header> <nav></nav> <div id="pagecontent"></div> <footer></footer> </div> <!-- featured articles/homepage template --> <script type="text/template" id="featuredarticles"> <link rel="stylesheet" href="css/homepagecontent.css" /> <section id="banner"></section> <aside> <div></div> <div></div> </aside> <section id="main"></section> <section id="opinion"> <div></div> <div></div> <div></div> </section> <section id="travel"> <div></div> <div></div> <div></div> </section> </script> <!-- content articles template --> <script type="text/template" id="contentarticles"> <link rel="stylesheet" href="css/categorypagecontent.css" /> <section id="main"></section> <aside></aside> </script> <!-- require.js reference --> <script src="/js/libs/require.js" data-main="/js/app.js"></script> </body>

can / should externalize html instead. if so, how externalize (i.e. using view) follows:

<!-- featured articles/homepage template --> <script type="text/template" id="featuredarticles"> <!-- html rendered externally --> </script> <!-- content articles template --> <script type="text/template" id="contentarticles"> <!-- html rendered externally --> </script>

here snippet of how render template view:

define(['underscore', 'backbone', 'collections/bannercollection', 'collections/featuredarticlescollection', ], function (_, backbone, bannercollection, featuredarticlescollection) { var featuredarticlesview = backbone.view.extend({ el: $('#pagecontent'), initialize: function () { this.render(); }, render: function () { var = this; var template = _.template($('#featuredarticles').html(), {}); that.$el.html(template); homecoming that; } }); homecoming featuredarticlesview; });

i have been reading partials, need guidance on best practice , if / how inline html should broken out.

i found while little snippet of template manager (can't remember author, sorry):

templatemanager = { templates: {}, // holds templates cache get: function(id, callback){ var template = this.templates[id]; if (template) { // homecoming cached version if exists callback(template); } else { var = this; // fetch, cache , homecoming template $.get(id + ".html", function(template) { that.templates[id] = template; callback(that.templates[id]); }); } } };

it fetches template file, caches , calls callback function after loaded, this:

templatemanager.get('path/to/your/template', function(resp) { // resp template markup homecoming this; });

hope helps.

update

here working fiddle:

http://jsfiddle.net/411jgf78/1/

javascript html backbone.js underscore.js

No comments:

Post a Comment