Last active
August 12, 2023 18:50
-
-
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.
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
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script takes two arguments:
json
fileIt 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
anddata.json
are your files.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