Branny
Branny

Reputation: 178

Generate static HTML files from ejs templates

OK, so I have my basic nodejs website up and running. It's all working and runs through a node server - using my basic-node-site

It uses ejs as the templating engine.

I'd like to release these templates as a static website. So all generated locally and it exports all my pages to static HTML files that I can publish on my basic hosting platform. no server side technology required.

I've had a look at jade, but it required me to change the templating and the structure.

Is there any tool out there that just publishes my current setup to a folder with all the generated html files??

Thanks for any help. It's appreciated.

Upvotes: 9

Views: 8196

Answers (1)

MJPinfield
MJPinfield

Reputation: 796

As long as you have the EJS npm package installed you can compile it.

var fs = require('fs'),
    ejs = require("ejs");

function ejs2html(path, information) {
    fs.readFile(path, 'utf8', function (err, data) {
        if (err) { console.log(err); return false; }
        var ejs_string = data,
            template = ejs.compile(ejs_string),
            html = template(information);
        fs.writeFile(path + '.html', html, function(err) {
            if(err) { console.log(err); return false }
            return true;
        });  
    });
}

ejs2html(__dirname+"/index.ejs")
  • Path: the location of the file, include __dirname or it wont work
  • Information: the information to be compiled like {users: ['bill','bob']} (optional)

EJS

Reading file in NodeJS

Edit

I made the code work and tested it, the ejs file will be compiled and written to the same directory with .html appended to the end.

Upvotes: 13

Related Questions