The LB.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.
npm install --save lb.generator.handlebars
node generate.js
const Generator = require('lb.generator.handlebars');
// 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" }
]
}
]
};
Create a Handlebars template file: ./sample-templates/sample.hbs
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
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');
- 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();
}
});