Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node express how to render handlebars html page to file

I want to convert some html page to pdf via wkhtmltopdf. However, the html page I want to convert to pdf is dynamically generated using handlebars.

So I think one solution maybe to generate the html page via handlebars but to a file (html file). Then, convert that file to pdf using hkhtmltopdf, then allow the user to, somehow, download the pdf.

So, my question is: how can I render the (handlebars) dynamically generated html page to a file?

Thanks and bye ...

like image 885
Manuel Rivera Avatar asked May 04 '15 12:05

Manuel Rivera


People also ask

Can I use handlebars on HTML?

An HTML <script> element with type value of text/x-handelbars-template can be used to contain Handlebars. js template text and expressions. This allows writing Handlebars. js templates in an HTML document.


2 Answers

Using express-handlebars, you should use the advanced mode and create an instance of it like in this example.

The proper way would be to create a view file (like you probably already have per you question) and use the express handlebars instance to render it:

// init code
var exphbs = require('express-handlebars');
var hbs = exphbs.create({
    defaultLayout: 'your-layout-name',
    helpers: require("path-to-your-helpers-if-any"),
});
app.engine('.file-extention-you-use', hbs.engine);
app.set('view engine', '.file-extention-you-use');

// ...then, in the router
hbs.render('full-path-to-view',conext, options).then(function(hbsTemplate){
     // hbsTemplate contains the rendered html, do something with it...
});

HTH

like image 133
Hertzel Guinness Avatar answered Nov 10 '22 14:11

Hertzel Guinness


Simple example for create file.

var Handlebars = require('handlebars');

var source = "<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
    "{{kids.length}} kids:</p>" +
    "<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
var template = Handlebars.compile(source);

var data = { "name": "Alan", "hometown": "Somewhere, TX",
    "kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
var result = template(data);


var fs = require('fs');
    fs.writeFile("test.html", result, function(err) {
    if(err) {
        return console.log(err);
    }
});
like image 16
Alex Khlebaev Avatar answered Nov 10 '22 14:11

Alex Khlebaev