• Stars
    star
    147
  • Rank 251,347 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 5 years ago

Reviews

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

Repository Details

A sane Gulp plugin to compile Handlebars templates. Useful as a static site generator.

gulp-hb

NPM version Downloads Build Status Coverage Status Tip

A sane static Handlebars Gulp plugin. Useful as a static site generator. Powered by handlebars-wax. Think Assemble, but with a lot less Jekyll baggage.

To precompile templates into JavaScript, see gulp-handlebars.

Install

$ npm install --save-dev gulp-hb

Usage

const gulp = require('gulp');
const hb = require('gulp-hb');

// Basic

function basic() {
    return gulp
        .src('./src/{,posts/}*.html')
        .pipe(hb()
            .partials('./src/assets/partials/**/*.hbs')
            .helpers('./src/assets/helpers/*.js')
            .data('./src/assets/data/**/*.{js,json}')
        )
        .pipe(gulp.dest('./web'));
}

gulp.task('basic', basic);

// Advanced

function advanced() {
    const hbStream = hb({ debug: true })
        // Partials
        .partials('./partials/components/**/*.{hbs,js}')
        .partials('./partials/layouts/**/*.{hbs,js}')
        .partials({
            boo: '{{#each boo}}{{greet}}{{/each}}',
            far: '{{#each far}}{{length}}{{/each}}'
        })

        // Helpers
        .helpers(require('handlebars-layouts'))
        .helpers('./helpers/**/*.js')
        .helpers({
            foo: function () { ... },
            bar: function () { ... }
        })

        // Decorators
        .decorators('./decorators/**/*.js')
        .decorators({
            baz: function () { ... },
            qux: function () { ... }
        })

        // Data
        .data('./data/**/*.{js,json}')
        .data({
            lorem: 'dolor',
            ipsum: 'sit amet'
        });

    return gulp
        .src('./src/{,posts/}*.html')
        .pipe(hbStream)
        .pipe(gulp.dest('./web'));
}

gulp.task('advanced', advanced);

Template Context

The template context is a merge of pre-registered data and file-specific data. Pre-registered data is available to all templates and is set using the .data() method. File-specific data is available to the current template and is set via the file.data property.

@ Data Variables

@root

The merged object of pre-registered data and file-specific data is available as the primary context of your templates. In cases where accessing this data would require the use of ../, you may access the top-level context via @root:

{{ foo }}
{{ @root.foo }}

{{#each bar}}
    {{ ../foo }}
    {{ @root.foo }}
{{/each}}
@global

In cases where file-specific data keys collide with pre-registered data keys, you may access the pre-registered data via @global:

{{ @global.foo }}
@local

In cases where pre-registered data should be ignored, you may access the file-specific data via @local.

{{ @local.foo }}
@file

In cases where information about the template file itself is needed, you may access the file object via @file:

{{ @file.path }}

File-specific Data Sources

File-specific data is set via the file.data property using other plugins such as gulp-data, gulp-data-json, or gulp-front-matter.

const gulp = require('gulp');
const data = require('gulp-data');
const frontMatter = require('gulp-front-matter');
const hb = require('gulp-hb');

function inject() {
    return gulp
        .src('./src/*.html')

        // Load an associated JSON file per post.
        .pipe(data((file) => {
            return require(file.path.replace('.html', '.json'));
        }))

        // Parse front matter from post file.
        .pipe(frontMatter({
            property: 'data.frontMatter'
        }))

        // Data for everyone.
        .pipe(hb().data('./data/**/*.js'))

        .pipe(gulp.dest('./web'));
}

gulp.task('inject', inject);

Multiple Data Sources

Multiple data sources can be used to render the same set of templates to different directories using through2.

const gulp = require('gulp');
const hb = require('gulp-hb');
const through = require('through2');

function i18n() {
    return gulp
        .src('./i18n/*.json')
        .pipe(through.obj((file, enc, cb) => {
            const locale = file.stem;
            const data = {
                locale: locale,
                i18n: JSON.parse(file.contents.toString())
            };

            gulp
                .src('./templates/**/*.html')
                .pipe(hb().data(data))
                .pipe(gulp.dest('./dist/' + locale))
                .on('error', cb)
                .on('end', cb);
        }));
}

gulp.task('i18n', i18n);

API

hb([options]): TransformStream

  • options {Object} (optional) Passed directly to handlebars-wax so check there for more options.
    • bustCache {Boolean} (default: true) Force reload data, partials, helpers, and decorators.
    • cwd {String} (default: process.cwd()) Current working directory.
    • debug {Boolean|Number} (default: false or 0) Whether to log registered functions and data (true or 1) and glob parsing (2).
    • handlebars {Handlebars} (optional) A specific instance of Handlebars, if needed.
    • compileOptions {Object} Options to use when compiling templates.
    • templateOptions {Object} Options to use when rendering templates.
    • partials {String|Array.<String>|Object|Function(handlebars)}
    • parsePartialName {Function(options, file): String}
    • helpers {String|Array.<String>|Object|Function(handlebars)}
    • parseHelperName {Function(options, file): String}
    • decorators {String|Array.<String>|Object|Function(handlebars)}
    • parseDecoratorName {Function(options, file): String}
    • data {String|Array.<String>|Object}
    • parseDataName {Function(options, file): String}

Returns a Gulp-compatible transform stream that compiles Handlebars templates to static output.

.partials(pattern [, options]): TransformStream

  • pattern {String|Array<String>|Object|Function(handlebars)}
  • options {Object} Same options as hb().

Loads additional partials. See handlebars-wax.

.helpers(pattern [, options]): TransformStream

  • pattern {String|Array<String>|Object|Function(handlebars)}
  • options {Object} Same options as hb().

Loads additional helpers. See handlebars-wax.

.decorators(pattern [, options]): TransformStream

  • pattern {String|Array<String>|Object|Function(handlebars)}
  • options {Object} Same options as hb().

Loads additional decorators. See handlebars-wax.

.data(pattern [, options]): TransformStream

  • pattern {String|Array<String>|Object}
  • options {Object} Same options as hb().

Loads additional data. See handlebars-wax.

Contribute

Standards for this project, including tests, code coverage, and semantics are enforced with a build tool. Pull requests must include passing tests with 100% code coverage and no linting errors.

Test

$ npm test

MIT © Shannon Moeller

More Repositories

1

handlebars-layouts

Handlebars helpers which implement layout blocks similar to Jinja, Nunjucks (Swig), Pug (Jade), and Twig.
JavaScript
359
star
2

reset-css

An unmodified* copy of Eric Meyer's CSS reset. PostCSS, webpack, Sass, and Less friendly.
Less
333
star
3

up

Quickly navigate to a parent directory via tab-completion.
Shell
160
star
4

ygor

Task toolkit. For when `npm run` isn't enough and everything else is too much.
JavaScript
68
star
5

find-config

Like findup-sync, but 2-4x faster and supports XDG-style `.config/` directories.
JavaScript
40
star
6

handlebars-wax

The missing Handlebars API for data, partials, helpers, and decorators.
JavaScript
38
star
7

regx

Tagged-template-string regular-expression compiler.
JavaScript
34
star
8

front-end-logo

A community logo for front-end web development.
32
star
9

cli-columns

Columnated lists for the CLI. Unicode and ANSI safe.
JavaScript
31
star
10

require-glob

Requires multiple modules using glob patterns and combines them into a nested object.
JavaScript
21
star
11

mute

Politely tells stdout and stderr to shut the heck up for a moment.
JavaScript
11
star
12

handlebars-group-by

Handlebars helper which allows you to group lists by a property of each item.
JavaScript
10
star
13

spiff

Promise-aware file-system adapter and transmogrifier.
JavaScript
9
star
14

apply-html

It's `.innerHTML = ''` for the 21st century.
JavaScript
7
star
15

livery

CLI to reload browsers when files change with LiveReload.
JavaScript
7
star
16

todomvc-custom-elements

TodoMVC app built using Custom Elements and up-and-coming vanilla code in the browser and on the server.
JavaScript
7
star
17

bulk

Executes a command across multiple subdirectories.
Shell
7
star
18

deduce

Ridiculously easy JavaScript state containers with action methods.
JavaScript
7
star
19

pardy

Websocket-based trivia game.
JavaScript
6
star
20

whim

A protean Node.js toolset based on my mercurial preferences.
JavaScript
6
star
21

esprev

It's Babel without the setup pain. Like the original 6to5.
JavaScript
5
star
22

dotfiles

.files 📂
Shell
5
star
23

run-headless

The easiest way to run code in a headless browser.
JavaScript
5
star
24

rollup-preset-isomorphic

Everything you need to rollup isomorphic modules.
JavaScript
4
star
25

talks

Supporting material for my public presentations.
JavaScript
4
star
26

list-promise

Maximally-concurrent Promise-based array iteration.
JavaScript
4
star
27

gulp-promisify

Enables use of Promises or async/await keywords to control the flow of Gulp tasks.
JavaScript
4
star
28

vanilla-mvc-demo

Demo MVC app written in vanilla JS, with dependency injection, services, templates, and factories.
JavaScript
3
star
29

todomvc-vanilla

A TodoMVC example using minimal tooling and evergreen vanilla features.
JavaScript
3
star
30

babel-browserify-nyc-tape-zuul-isomorphic-demo

An isomorphic JavaScript development stack with tests and code coverage using babel, browserify, nyc, tape, and zuul.
JavaScript
3
star
31

code

code 🗃️
JavaScript
2
star
32

vanilla-zero

Modern web development with zero calories.
CSS
2
star
33

trivia

trivia 🧐
JavaScript
2
star
34

isomorphic-boilerplate

Isomorphic JS project boilerplate using babel, browserify, gulp, and tape.
JavaScript
1
star
35

async-map-stream

JavaScript
1
star
36

get-context

Chainable canvas context api wrapper.
JavaScript
1
star
37

vinyl-rw

A file-system aware vinyl file with first-class string support.
JavaScript
1
star
38

enceladus

Game Off 2020
JavaScript
1
star
39

isitchristmas

Is it Christmas?
HTML
1
star
40

infinite-improbability-drive

Infinite Improbability Drive
JavaScript
1
star
41

say-repl

A read-eval-print loop for the macOS `say` command.
JavaScript
1
star
42

advent-of-code

JavaScript
1
star