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
You 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!');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With