Jade locals with Gulp
One of the coolest features of Jade is the concept of locals: An object that can be passed to the compiler and used in the Jade code, allowing better separation of content and templates. Ideally, these locals are held in an external file.
After much tinkering, I figured something out:
var fs = require('fs');
...
.pipe( p.jade({
pretty: uglyLevel,
data: JSON.parse( fs.readFileSync('src/data.js', { encoding: 'utf8' }) )
}) )
…What?
- Gulp Jade’s docs show that the
dataorlocalsoption to could be used to pass in a single object holding all the external data. - File I/O, or
fsis node’s way of reading files. Using fs.readFileSync, I used aJSONfile to hold all the data. - JSON.parse() is a native JS method to convert a string (The output of
fs.readFileSyncwithutf8encoding) to JSON.
Combining the three resulted in the above one liner, allowing me to use a data.js file to host all raw data and use loops to better template the code within. Win!