Last active
December 16, 2015 18:58
-
-
Save swissmanu/5481272 to your computer and use it in GitHub Desktop.
Creates precompiled handlebar templates and makes them available as a basic common js module. Change the paths templatesSource and templatesDestination to your needs. Simply execute with "node templatePrecompiler.js"
This file contains 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
/** File: Template Preprocessor | |
* Creates precompiled handlebar templates and makes them available as a simple | |
* common js module. | |
*/ | |
var Handlebars = require('handlebars') | |
, _ = require('underscore') | |
, path = require('path') | |
, fs = require('fs') | |
, templatesSource = path.join(__dirname, 'src', 'templates') | |
, templatesDestination = path.join(__dirname, 'src', 'templates', 'precompiledTemplates.js') | |
, templateFiles = fs.readdirSync(templatesSource) | |
, precompiledTemplates = {} | |
_.each(templateFiles, function(file) { | |
var ext = file.substr(file.length-4); | |
if(file && ext === '.hbs') { | |
var name = file.substr(0, file.length-4) | |
, rawTemplate = fs.readFileSync(path.join(templatesSource, file), 'utf-8') | |
, precompiledTemplate = Handlebars.precompile(rawTemplate); | |
if(precompiledTemplate) { | |
precompiledTemplates[name] = precompiledTemplate; | |
} | |
} | |
}); | |
if(_.keys(precompiledTemplates).length > 0) { | |
var templateModule = | |
'var Handlebars = require(\'handlebars\')\n' + | |
' , template = Handlebars.template;\n'; | |
_.each(precompiledTemplates, function(precompiledTemplate, name) { | |
templateModule += | |
'module.exports.' + name + ' = template(' + | |
precompiledTemplate + ');'; | |
}); | |
fs.writeFileSync(templatesDestination, templateModule, 'utf8') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment