In my efforts to create a straightforward live API endpoint (using res.json()
) within an Express 4 application that merges Handlebars templates with data and sends back a string for client-side HTML replacement, I've encountered a challenge.
The current obstacle involves using fs.readFile()
to access the content of the Handlebars template, whereas I would prefer to utilize a similar approach as used for displaying a standard view. Is there a way to achieve this?
Here is a simple example:
Data endpoint (JSON):
{
"title": "Page Title"
}
template.hbs:
<h1>{{ title }}</h1>
Live endpoint (JSON):
{
"tpl": "<h1>Page Title</h1>"
}
Functionality in my route response:
var api = {};
fs.readFile('template.hbs', 'utf8', function(err, tpl) {
var template = hbs.compile(tpl);
// The 'data' variable holds the value returned from the data endpoint mentioned earlier
api.tpl = template(data);
res.json(api);
});
There might not be a need for concern about this, as Handlebars may handle these processes behind the scenes. However, I'm exploring if there exists a simpler method that I am currently unaware of.