This example will show you how to compile partials and templates down to a single file.
The stream merging technique is from gulp's Using multiple sources in one task recipe.
gulp-declare
- Declare properties and sub-propertiesgulp-concat
- Combine output into a single filegulp-wrap
- Addrequire()
andHandlebars.template()
statementsmerge-stream
- Combine templates and partials into a single file stream
Type the following commands from the root of this repository:
npm install # install the plugin's dependencies
cd examples/partials
npm install # install the example's dependencies
gulp
open build/index.html
You should see the following output:
This is the app!
This is the partial!
# Note the specific version of Handlebars is specified here
npm install --save-dev gulp-handlebars gulp-wrap gulp-declare gulp-concat merge-stream
var path = require('path');
var gulp = require('gulp');
var wrap = require('gulp-wrap');
var declare = require('gulp-declare');
var concat = require('gulp-concat');
var merge = require('merge-stream');
var handlebars = require('gulp-handlebars');
gulp.task('templates', function() {
// Assume all partials start with an underscore
// You could also put them in a folder such as source/templates/partials/*.hbs
var partials = gulp.src(['source/templates/_*.hbs'])
.pipe(handlebars())
.pipe(wrap('Handlebars.registerPartial(<%= processPartialName(file.relative) %>, Handlebars.template(<%= contents %>));', {}, {
imports: {
processPartialName: function(fileName) {
// Strip the extension and the underscore
// Escape the output with JSON.stringify
return JSON.stringify(path.basename(fileName, '.js').substr(1));
}
}
}));
var templates = gulp.src('source/templates/**/[^_]*.hbs')
.pipe(handlebars())
.pipe(wrap('Handlebars.template(<%= contents %>)'))
.pipe(declare({
namespace: 'MyApp.templates',
noRedeclare: true // Avoid duplicate declarations
}));
// Output both the partials and the templates as build/js/templates.js
return merge(partials, templates)
.pipe(concat('templates.js'))
.pipe(gulp.dest('build/js/'));
});
<script src="js/templates.js"></script>
You may also concatenate into your build output if you like. See gulp-concat
for more info.
<script>
// This will render the template defined by App.hbs
document.querySelector('#app').innerHTML = MyApp.templates.App();
</script>