I'm building a static site using Handlebars and Gulp. Here's my folder structure:
app/
content/
intro.json
header.json
faq.json
features.json
footer.json
templates/
home.hbs
partials/
home-section.hbs
header.hbs
footer.hbs
index.html
Gulpfile.js
The content of home.hbs is this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
{{> header}}
{{> home-section}}
{{> home-section}}
{{> home-section}}
{{> footer}}
</body>
</html>
I want to pass in intro.json
, faq.json
, and features.json
to each of the home-section
partials, and header.json
to header
and footer.json
to footer.
This is what I have in my Gulpfile so far:
var gulp = require('gulp');
var handlebars = require('gulp-compile-handlebars');
var rename = require('gulp-rename');
gulp.task('html', function() {
return gulp.src('./app/templates/*.hbs')
.pipe(handlebars({}, {
ignorePartials: true,
batch: ['./app/templates/partials']
}))
.pipe(rename({
extname: '.html'
}))
.pipe(gulp.dest('build'));
});
I haven't been able to figure out how to pass more than one JSON file at a time, especially to the home-section
s. Thanks in advance!
The first parameter to
handlebars
is your global context, available to all your templates. You can load your individual JSON files into a context object, and use that as the first parameter.(There's definitely better ways to do this, but hey, it's quick and easy!)
You can then pass these objects through the global context to your handlebars function
Once the data is inside your context, you can access it like this:
Inside your
home-section
partial, you'll have acontent
object that will contain the data of the file you passed into it. So, if yourinfo.json
file looked like this:Your
home-content.hbs
partial could then access the data like this: