I'm trying to create a Gulp task that applies two Handlebars processes to a src.
The first process uses an external JSON data source and populates a template. Then for an additional process, I want to parse another expression in the template with a value calculated in my gulpfile.
The resulting template is then renamed and output to a destination.
Each process works independently but when I try to combine them into a single task only the first Handlebars process is run.
gulp.src('handlebars/pagetemplate.hbs')
.pipe( handlebars(dataSrc1, options) )
.pipe( handlebars(dataSrc2, options) )
.pipe( rename('page.html') )
.pipe( gulp.dest('outputfolder/') );
Have I misunderstood how Gulp's pipe stream works? I have had the idea to merge the two JSON sources first and then parse with Handlebars but I'm unsure on the syntax for this in the above context.
The reason your code doesn't work is because after the first handlebars()
you no longer have a Handlebars template in your stream. All the {{placeholder}}
expressions have been replaced and you're left with nothing but HTML. So the second handlebars()
can't actually do anything anymore.
I have had the idea to merge the two JSON sources first and then parse with Handlebars
That's the correct approach.
Say your first data source is a file data.json
and the second is computed in your Gulpfile. You can use the merge
package to merge the two:
var merge = require('merge');
gulp.task('default', function() {
var dataSrc1 = require('./data.json');
var dataSrc2 = {
count: 40 + 2
};
var dataSrc = merge.recursive(true, dataSrc1, dataSrc2);
return gulp.src('handlebars/pagetemplate.hbs')
.pipe(handlebars(dataSrc, options))
.pipe(rename('page.html'))
.pipe(gulp.dest('outputfolder/'));
});