Compile Handlebars templates and partials in Gulp

var gulp        = require('gulp'),
    uglify        = require('gulp-uglify'),
    rename        = require('gulp-rename'),
    concat        = require('gulp-concat'),
    handlebars    = require('gulp-handlebars'),
    wrap        = require('gulp-wrap'),
    path        = require('path'),
    htmlclean    = require('gulp-htmlclean'),
    merge        = require('merge-stream'),
    declare        = require('gulp-declare'),
    source        = require('vinyl-source-buffer'),

/**
 * Compile handlebars templates
 */
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( partials_source )
        .pipe( htmlclean() )
        .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( templates_source )
        .pipe( htmlclean() )
        .pipe( handlebars() )
        .pipe( wrap('Handlebars.template(<%= contents %>)') )
        .pipe( declare({
            namespace : 'Publish.templates',
            noRedeclare : true
        }));

    return merge(partials, templates)
        .pipe( uglify() )
        .pipe( concat( 'publish.templates.js' ) )
        .pipe( rename( { suffix : '.min' } ) )
        .pipe( gulp.dest('./publish/assets/js') );
});

 

Passing data to Handlebars partials

If you have this:

const dummy_data = {
                toplinks : ['Shop','Publish','Read'],
                is_staff : true,
                latam : false,
                user : {
                    is_authenticated : true,
                    first_name : "John",
                    last_name : "Doe"
                },
                currentLanguage : 'DA',
                language : [
                    'DA',
                    'EN'
                ]
            };

        var template = Publish.templates.navigation,
            output = template( dummy_data );

            $('body').prepend( output );

Do this in the main template:

{{> toplinks toplinks=this.toplinks staff=this.is_staff}}

And this in the partial:

{{#each toplinks}}
    <a href="{{this}}" target="_blank" class="nav-btn">{{this}}</a>
{{/each}}

{{#if staff}}
    <a href="#" target="_top" class="nav-btn">Admin</a>
{{/if}}