• Stars
    star
    171
  • Rank 222,266 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Handlebars plugin for gulp

gulp-handlebars NPM version Build status

Handlebars plugin for gulp

Usage

Install gulp-handlebars as a development dependency:

npm install --save-dev gulp-handlebars

VERSION MISMATCH ERROR?!

Are you seeing this error when using pre-compliled templates?

Error: Template was precompiled with an older version of Handlebars

If you're getting a version mismatch error when using pre-compliled templates, install the handlebars version of your choice and pass it as options.handlebars, then include the appropriate runtime in your client-side application.

Here's how you install your own version of handlebars:

npm install --save handlebars@^4.0.0

And here's how you use that verison of handlebars in gulp-handlebars:

handlebars({
  handlebars: require('handlebars')
})

The runtime is located in:

node_modules/handlebars/dist/handlebars.js

Compiling templates for the browser

gulp-declare and gulp-wrap can be used to safely declare template namespaces and make templates available for use in the browser.

First, install development dependencies:

npm install --save-dev gulp-handlebars gulp-wrap gulp-declare gulp-concat

Given the following directory structure:

├── gulpfile.js              # Your gulpfile
└── source/                  # Your application's source files
    └── templates/           # A folder containing templates named with dot notation
        └── home.header.hbs  # A template that will be available as MyApp.templates.home.header

To compile all templates in source/templates/ to build/js/templates.js under the MyApp.templates namespace:

gulpfile.js

var handlebars = require('gulp-handlebars');
var wrap = require('gulp-wrap');
var declare = require('gulp-declare');
var concat = require('gulp-concat');

gulp.task('templates', function(){
  gulp.src('source/templates/*.hbs')
    .pipe(handlebars())
    .pipe(wrap('Handlebars.template(<%= contents %>)'))
    .pipe(declare({
      namespace: 'MyApp.templates',
      noRedeclare: true, // Avoid duplicate declarations
    }))
    .pipe(concat('templates.js'))
    .pipe(gulp.dest('build/js/'));
});

The template's filename is combined with the namespace, so the resulting build/js/templates.js would look like:

this["MyApp"] = this["MyApp"] || {};
this["MyApp"]["templates"] = this["MyApp"]["templates"] || {};
this["MyApp"]["templates"]["home"] = this["MyApp"]["templates"]["home"] || {};
this["MyApp"]["templates"]["home"]["header"] = Handlebars.template(function() { /* compiled template function */ });

Namespace templates according to nested directories

See the namespaceByDirectory example if you'd like to compile templates with a mapping that looks like this:

File path Namespace path
source/templates/App.hbs MyApp.templates.App
source/templates/App/header.hbs MyApp.templates.App.header
source/templates/App/footer.hbs MyApp.templates.App.footer
source/templates/Other.item.hbs MyApp.templates.Other.item

Compiling to various module systems

See the gulp-define-module documentation for details on how to define templates as AMD, Node, CommonJS, and hybrid modules.

See the amd example for a full example of compiling templates to AMD modules.

gulp-handlebars makes the following available for use in gulp-define-module's wrapper template option:

  • <%= handlebars %> - The Handlebars template, wrapped in a call to Handlebars.template()
  • <%= contents %> - The bare Handlebars template (not wrapped).

gulp-handlebars also sets a default options.require of { Handlebars: 'handlebars' } for gulp-define-module so Handlebars will be present in when defining AMD, Node, CommonJS, or hybrid modules. You can change this by passing a different options.require when you invoke gulp-define-module.

Compiling partials

The following example will precompile and register partials for all .hbs files in source/partials/, then store the result as build/js/partials.js;

var path = require('path');
var gulp = require('gulp');
var wrap = require('gulp-wrap');
var concat = require('gulp-concat');
var handlebars = require('gulp-handlebars');

gulp.task('partials', function() {
  // Assume all partials are in a folder such as source/partials/**/*.hbs
  gulp.src(['source/partials/**/*.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'));
        }
      }
    }))
    .pipe(concat('partials.js'))
    .pipe(gulp.dest('build/js/'));
});

See the partials example for a full example that compiles partials and templates down to a single file.

Compiling using a specific Handlebars version

You can use different versions of Handlebars by specifying the version in your package.json and passing it as options.handlebars:

package.json

{
  "devDependencies": {
    "handlebars": "^1.3.0"
  }
}

gulpfile.js

gulp.task('templates', function(){
  gulp.src('source/templates/*.hbs')
    .pipe(handlebars({
      handlebars: require('handlebars')
    }))
    .pipe(wrap('Handlebars.template(<%= contents %>)'))
    .pipe(declare({
      namespace: 'MyApp.templates',
      noRedeclare: true, // Avoid duplicate declarations
    }))
    .pipe(concat('templates.js'))
    .pipe(gulp.dest('build/js/'));
});

The runtime you include on the client side MUST match the version you compile templates with. You cannot use the the 2.x runtime with 1.x templates. The handlebars1 example copies the runtime from node_modules/handlebars/dist/handlebars.runtime.js and uses that on the client side. Follow a similar pattern in your application to keep the runtime up to date with the compiler.

Compiling to separate modules for Node/Browserify

This example will make templates available for loading via Node's require:

gulpfile.js

var handlebars = require('gulp-handlebars');
var defineModule = require('gulp-define-module');

gulp.task('templates', function(){
  gulp.src(['templates/*.hbs'])
    .pipe(handlebars())
    .pipe(defineModule('node'))
    .pipe(gulp.dest('build/templates/'));
});

Templates can then be used within Node as such:

var appTemplate = require('./build/templates/App.Header.js');
var html = appTemplate(data);

Compiling to a single module for use in Node/Browserify

See the singleModule example if you'd like to have a single module that contains all of your templates that can be used like so:

yourApp.js

var templates = require('./templates');
var output = templates.App.header();

Processing the generated template AST

The example below removes any partial and replaces it with the text foo.

gulpfile.js

handlebars({
  processAST: function(ast) {
    ast.statements.forEach(function(statement, i) {
      if (statement.type === 'partial') {
        ast.statements[i] = { type: 'content', string: 'foo' };
      }
    });
  }
})

Using HTMLBars with Ember

See the ember-htmlbars example for details

handlebars({
  handlebars: emberHandlebars,
  compiler: emberTemplateCompilerFunction
})

API

handlebars(options)

options.compilerOptions

Type: Object

Compiler options to pass to Handlebars.precompile().

options.processAST

Type: Function

A function which will be passed the parsed Handlebars Abstract Syntax Tree. You can modify the AST in place or return a new AST to change the source of the precompiled template.

options.handlebars

Type: Object

Handlebars library to use for precompilation. By default, the latest stable version of Handlebars is used.

options.compiler

Type: Function

Custom compiler function. By default, the precompile method of the provided Handlebars module is used (see options.handlebars).

More Repositories

1

iNoBounce

Stop your iOS webapp from bouncing around when scrolling
JavaScript
1,334
star
2

gulp-replace

A string replace plugin for gulp
JavaScript
496
star
3

mdn.io

The "I'm feeling lucky" URL shortener
JavaScript
215
star
4

gulp-karma

Karma plugin for gulp
JavaScript
75
star
5

gulp-csslint

CSSLint plugin for gulp
JavaScript
74
star
6

PseudoClass

An OOP framework for Node.js and the browser
JavaScript
66
star
7

DOMly

The fast template system that creates and clones DOM nodes
JavaScript
53
star
8

wellTested

A simple todo app tested with Karma, Jasmine, CasperJS, and Istanbul
JavaScript
45
star
9

scopedQuerySelectorShim

querySelector/querySelectorAll shims that enable the use of :scope
JavaScript
41
star
10

iOCSS

Simple, resolution independent, image-free CSS for mobile web applications
CSS
36
star
11

F

F, a Backbone component framework that encourages code re-use
JavaScript
23
star
12

Pinky

A straight-forward Promises/A+ 1.1 implementation
JavaScript
22
star
13

VoodooI2CGoodix

VoodooI2C satellite driver for Goodix touchscreens in C++
C++
20
star
14

gulp-declare

Safely declare namespaces and set their properties
JavaScript
17
star
15

quadtag

An Arduino-based laser tag system for quadcopters
Arduino
15
star
16

DuneBuggy

A 3D multiplayer dune buggy battle game written entirely in JavaScript
JavaScript
10
star
17

flexless

LESS mixins for the CSS Flexible Box Layout Module 2012 Editor's Draft with optional fallbacks for the 2009 W3C Working Draft.
9
star
18

karma-benchmark-reporter

A jsPerf-style reporter for karma-benchmark
JavaScript
5
star
19

TankGame

A 3D multiplayer tank battle game written entirely in JavaScript
JavaScript
5
star
20

nsdeclare

Safely declare a namespace using dot notation
JavaScript
5
star
21

stompinator

Elephant activity tracking (upstairs neighbor stomping) device for M5Stack Core2
C++
5
star
22

coronaglobe

Heatmap representation of COVID-19 on WebGl 3D world map
JavaScript
5
star
23

wolf4sdl-controller-mappings

A selection of controller mappings for wolf4sdl
4
star
24

fui

A flat UI library for the web
JavaScript
4
star
25

karma-benchmark-example

A karma-benchmark example
JavaScript
4
star
26

platformer

A platformer experiment
JavaScript
3
star
27

piControl

A client-server system for controlling the Raspberry Pi
JavaScript
3
star
28

gulp-karma-test

A repository dedicated to figuring out how to use Karma and gulp together without wanting to off one's self with a rusty spoon
JavaScript
3
star
29

coronadatascraper-cache

Cache for the coronadatascraper project
HTML
2
star
30

lazd.github.io

lazd's blog
HTML
2
star
31

shellcolor

ANSI colors for your Node.js app's stdout, stderror, and logs
JavaScript
2
star
32

commonesm

How to publish a module, maintain support for CommonJS, and test with jest
JavaScript
1
star
33

DOMly-cli

JavaScript
1
star
34

dilBot-rc

JavaScript
1
star
35

gulp-domly

DOMly plugin for gulp 3
JavaScript
1
star
36

coronavirus-data-sources

A list of coronavirus data sources by county
1
star
37

SimpleExpressServer

An express+Stylus server ala Python's SimpleHTTPServer
JavaScript
1
star
38

expressSeed

A Node.js + express app structure
1
star
39

grunt-domly

Grunt task to precompile DOMly templates
JavaScript
1
star
40

wolf4sdl

Wolf4SDL is an open-source port of id Software's classic first-person shooter Wolfenstein 3D to the cross-platform multimedia library SDL. It is meant to keep the original feel while taking advantage of some improvements.
C++
1
star