Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Last active August 12, 2023 18:50
Show Gist options
  • Save isurfer21/a14822ae82cd493feb7e7c14c4ca8647 to your computer and use it in GitHub Desktop.
Save isurfer21/a14822ae82cd493feb7e7c14c4ca8647 to your computer and use it in GitHub Desktop.
A CLI app which compiles the template with handlebars, renders it with the data, and prints the output html to the console.
// Import the required modules
const fs = require('fs');
const path = require('path');
const handlebars = require('handlebars');
// Get the template and data file names from the command line arguments
const templateFile = process.argv[2];
const dataFile = process.argv[3];
// Check if the files exist and are valid
if (!templateFile || !dataFile) {
console.error('Usage: node script.js template.hbs data.json');
process.exit(1);
}
if (!fs.existsSync(templateFile) || path.extname(templateFile) !== '.hbs') {
console.error('Invalid template file: ' + templateFile);
process.exit(1);
}
if (!fs.existsSync(dataFile) || path.extname(dataFile) !== '.json') {
console.error('Invalid data file: ' + dataFile);
process.exit(1);
}
// Read the template and data files
const template = fs.readFileSync(templateFile, 'utf8');
const data = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
// Compile the template with handlebars
const compiledTemplate = handlebars.compile(template);
// Render the template with the data
const output = compiledTemplate(data);
// Print the output html to the console
console.log(output);
@isurfer21
Copy link
Author

This script takes two arguments:

  • a handlebars template file
  • a data json file

It reads the files, compiles the template with handlebars, renders it with the data, and prints the output html to the console.

You can run this script by typing below command in your terminal, where template.hbs and data.json are your files.

node handlebars-cli.js template.hbs data.json

You can also redirect the output to a file by adding > output.html at the end of the command, e.g.,

node handlebars-cli.js template.hbs data.json > output.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment