I want to generate a file from a template. For example, I have a handlebars (but it can be another template) like this
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
Then, I make a query to the database, and return the view to the browser. But now, I dont want return the view, but save it as a file on the server disk. How can I do it?
I try generate and save from the browser, but I want do the proccess in the server
I want to generate a file from a template. For example, I have a handlebars (but it can be another template) like this
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
Then, I make a query to the database, and return the view to the browser. But now, I dont want return the view, but save it as a file on the server disk. How can I do it?
I try generate and save from the browser, but I want do the proccess in the server
Share Improve this question asked Oct 10, 2016 at 16:39 Giancarlo VenturaGiancarlo Ventura 8572 gold badges11 silver badges27 bronze badges 3 |1 Answer
Reset to default 20You have to "compile" the template manually and write the result into the respective file. Like:
const fs = require('fs');
const Handlebars = require('handlebars');
const source = '<div>{{title}}</div>';
const template = Handlebars.compile(source);
const contents = template({title: 'Wohooo!'});
fs.writeFile('contents.html', contents, err => {
if (err) {
return console.error(`Autsch! Failed to store template: ${err.message}.`);
}
console.log(`Saved template!');
});
fs.writeFile
? – Bergi Commented Oct 10, 2016 at 17:00