Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 931
Branny Avatar asked Jun 22 '15 09:06

Branny


People also ask

How do I embed EJS in HTML?

Use <% - include( 'RELATIVE/PATH/TO/FILE' ) %> to embed an EJS partial in another file. The hyphen <%- instead of just <% to tell EJS to render raw HTML. The path to the partial is relative to the current file.

Can I use EJS instead of HTML?

As mentioned earlier, EJS is one of the most popular template engines for JavaScript. One of the reasons to choose it is that EJS code looks like pure HTML. It retains the syntax of HTML while allowing data interpolation, unlike Pug (another template engine) which uses a different syntax with indentation and spaces.

Is EJS static?

ejs-static-converter allows you to convert a node app that uses the EJS templating engine into a static HTML site, independant from any server code. This is useful for converting apps or websites that were made with node and ejs for easier development but don't require any server-side code into static HTML.


1 Answers

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.

like image 69
MJPinfield Avatar answered Sep 25 '22 10:09

MJPinfield