Created
February 5, 2013 17:10
-
-
Save darkargon/4715918 to your computer and use it in GitHub Desktop.
Watches HBS partials.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 2013 Filip Weiss | |
var fs = require("fs"); | |
var path = require("path"); | |
// config | |
var partialsDir = __dirname + '/../views/partials'; | |
var hbs; | |
exports.watch = function(_partialsDir, _hbs){ | |
hbs = _hbs; | |
partialsDir = _partialsDir; | |
fs.watch(partialsDir, function(event, filename){ | |
var file = partialsDir + "/" + filename; | |
if (event == "rename"){ | |
if(fs.existsSync(file)) registerPartial(file); | |
else unregisterPartial(file); | |
} else if(fs.existsSync(file)) registerPartial(file); | |
}); | |
updateAllPartials(hbs); | |
}; | |
function registerPartial(f){ | |
var filename = path.basename(f); | |
var matches = /^([^.]+).html$/.exec(filename); | |
if (!matches) return; | |
var name = matches[1]; | |
var template = fs.readFileSync(f, 'utf8'); | |
hbs.registerPartial(name, template); | |
} | |
function unregisterPartial(f){ | |
var filename = path.basename(f, '.html'); | |
if (hbs.handlebars.partials[filename] !== undefined) delete hbs.handlebars.partials[filename]; | |
else return; | |
} | |
function updateAllPartials(hbs){ | |
var filenames = fs.readdirSync(partialsDir); | |
filenames.forEach(function (filename) { | |
var matches = /^([^.]+).html$/.exec(filename); | |
if (!matches) return; | |
var name = matches[1]; | |
var template = fs.readFileSync(partialsDir + "/" + filename, 'utf8'); | |
hbs.registerPartial(name, template); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment