generator.handlebars
The Generator.Handlebars NPM package provides a template code generation library based on the Handlebars template engine. The library is easily installed via npm and provides a set of tools to generate any text-based asset from a JSON datasource.
Installation
npm install --save generator.handlebars
Test
node generate.js
Usage
1. Include the library
const Generator = require('generator.handlebars');
2. Load or define a model
// Load a model
const model = require("./sample-templates/sample-model.json");
// Or
// Define a model
const model = {
Description: "Test Model",
Items: [
{
Name: "ItemA",
Description: "Item - A",
Options: [
{ Id: "A", Description: "Option A" },
{ Id: "B", Description: "Option B" }
]
},
{
Name: "ItemB",
Description: "Item - B",
Options: [
{ Id: "C", Description: "Option C" },
{ Id: "D", Description: "Option D" }
]
}
]
};
3. Define a template
Create a Handlebars template file: ./sample-templates/sample.hbs
4. Define the template settings
Create a template settings file: ./sample-templates/sample.hbs.settings.json
{
"Target": "Items",
"TargetItem": "item",
"ExportPath": ".\\Generated\\Items\\\\{{item.Name}}.txt",
"AppendToExisting": false
}
Note: When using backslashes in a path, you must escape the backslashes an additional time if it precedes a Handldebars expression
5. Create a Template Loader
Create a Template Loader and pass it the path to the directory containing the templates. The loader will automatically load all template files ending in ".hbs" and their corresponding settings ".hbs.settings.json"
var loader = new Generator.TemplateLoader('./sample-templates');
6. Load and generate the templates
- Call the
loader.load()
function and pass a callback that recieves an array of loaded templates. - Iterate the loaded template array and call
template.generate()
for each template passing in your model. - Call
template.write()
on a generated template to write the generated template to its defined file.
// Load the templates
loader.load();
// Generate the loaded templates.
loader.generate(model, (loader) => { console.log("Templates Generated."); });
Or
// Load and generate
loader.loadAndGenerate(model, (loader) => { console.log('Templates loaded and generated.'); });
Or
// Load the templates with a callback containing the list of loaded templates
loader.load(function (templates) {
// Interate the templates and generate each with the supplied model
for (const template of templates) {
console.log(`Generating template: ${template.name}`)
// Generate the template
template.generate(model);
// Write the generated template to file
template.write();
}
});