handlebars.js - Packaging a Handlebars-based widget: javascript and html -


i'm relatively new this, please excuse if i'm missing obvious point...

i'd create reusable widget using handlebars, simplicity let's consider users table:

<script type="text/x-handlebars-template" id="temp1">        <table>          {{#users}}              <tr><td>{{name}}</td><td>{{email}}</td></tr>           {{/users}}         </table> </script>  <script>    var template=handlebars.compile($("#temp1").html());        function renderuserstable(users, divid){        $("#"+divid).html(template(users:users));    } <script> 

this works, got work template script (text/x-handlebars-template) embedded business page. that's not reusable: if need on page, i'll need copy-paste. considered quoting template javascript string variable, that's ugly since real html pretty large.

are there better practices, allow separate handlebars template dedicated file, included different pages needed?

thanks much

yes. 1 way use gulp task compile templates. example below takes individual handlebars files directory , puts them in 1 javascript file hb_templates.js templates. each template given name of file came from. example put template users.handlebars. include generated hb_templates.js after handlebars.js in production webpage.

gulp.task('handlebars', function() {   gulp.src('./app/views/*.handlebars')   .pipe(htmlmin({     collapsewhitespace: true   }))   .pipe(handlebars())   .pipe(wrap(function(data) {     var filename = data.file.history[0].split('\\').pop().split('.')[0];     return "handlebars.templates." + filename + "=handlebars.template(<%= contents %>)";   }))   .pipe(concat('hb_templates.js'))   .pipe(gulp.dest('./app/scripts/')); }); 

you use template this;

$("#"+divid).html(handlebars.templates.user(users:users)); 

since partials in handlebars templates can use these templates inside other template files so

<div> {{> user}} </div> 

just register them partials once have loaded hb_templates.js this;

handlebars.registerpartial('user', handlebars.templates.user); 

the example used following dependencies in nodejs gulp

{     "gulp": "3.9.0",     "gulp-concat": "2.6.0",     "gulp-handlebars": "4.0.0",     "gulp-htmlmin": "1.1.3",     "gulp-wrap": "0.11.0",     "handlebars": "3.0.3", } 

Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

android - How to create dynamically Fragment pager adapter -

1111. appearing after print sequence - php -