Render Handlebars templates seamlessly from strings or files, simplifying your templating workflow. Supports precompilation for enhanced performance.
npm install hbsr
bash
npm i hbsr
`
Usage
$3
`js
const hbsr = require('hbsr');
let source =
;
let data = {
firstName: "John",
date: "Nov 26, 1962",
author: "Jill"
}
let result = hbsr.render(source, data);
console.log(result);
`
$3
Create templates/letter.hbs with the following content:
`hbs
Dear {{{firstName}}}:
I am looking forward so seeing you on {{{date}}}!
Sincerely,
{{{author}}}
`
Create sample.js like this;
`js
const hbsr = require('hbsr');
let data = {
firstName: "John",
date: "Nov 26, 1962",
author: "Jill"
}
let templateBasename = 'letter';
let result = hbsr.render_template(templateBasename, data);
console.log(result);
`
Template options
Template options reside in hbsr.options property:
| Option | Description | Default |
| -------------------- | ---------------------------------- | ------------------------------------------------------- |
| template_path | Folder where template files reside | ./templates -- relative to scripts execution location |
| template_extension | Template file extension | .hbs -- extension added to basename parameter |
`js
const hbsr = require('hbsr');
// displays ./templates
console.log(hbsr.options.template_path);
// displays
console.log(hbsr.options.template_extension)
`
Override default template options to match your preferences:
`js
const hbsr = require('hbsr');
hbsr.options.template_path = '../../templates'; // templates reside two levels up inside template folder
// Set the new default template file extension to append to basename
// hbsr.options.template_extension = '.handlebars'
let data = {};
let r = hbsr.render_template('page', data); // use the ../../templates/page.hbs template
`
Using extra parameter to specify template options to match your preferences:
`js
const hbsr = require('hbsr');
let data = {};
// Specify the template_path to in this instance
// and use the default template extension
let r = hbsr.render_template('page', data, {'template_path': '../../templates'})
``