GreenTriangle
GreenTriangle

Reputation: 2460

Iterate a JSON object in Jade using gulp-data?

Goal

Use Gulp to render a Jade template that iterates over the items in a JSON array.

Problem

Try as I might, I can't work out a solution that lets me access fields in the JSON object. I've followed 4 separate tutorials word-for-word and I always wind up with cannot read property 'length' of undefined.

Code

items.json

{
    "wishlistItems": [
        {
            "name": "Boots",
            "price": 69.95,
            "notes": "Size 10"
        }
    ]
}

index.jade

doctype html
html
    body
        ul
            each item in wishlistItems
                li=item.name

gulpfile.js

const gulp = require('gulp');
const jade = require('gulp-jade');
const data = require('gulp-data');

gulp.task('default', ['build-jade']);

gulp.task('build-jade', () => {
    gulp.src('./src/index.jade')
        .pipe(data(file => require('./src/items.json')))
        .pipe(jade({locals: {}}))
        .pipe(gulp.dest('./dist/'));
});

Upvotes: 0

Views: 2974

Answers (1)

Sven Schoenung
Sven Schoenung

Reputation: 30564

Contrary to what the gulp-jade documentation says when you provide the locals option all data on the vinyl file object is ignored.

That means the following works:

gulp.task('build-jade', () => {
  gulp.src('./src/index.jade')
    .pipe(data(file => require('./src/items.json')))
    .pipe(jade())
    .pipe(gulp.dest('./dist/'));
});

If you want to provide both static locals as well as per-file data see the third code example under Use with gulp-data in the gulp-jade documentation.

Upvotes: 2

Related Questions