3

I've been used to PHP, where code is put in a file, and executed each time on load.

With NodeJS, I need to use HTML files, but need calculation done within the files. A solution would be putting the whole file's HTML content into the file that is running the HTTP server, but I'd like to have them in files instead.

I am using NodeJS, and Express. How is this done?

hexacyanide
  • 88,222
  • 31
  • 159
  • 162

2 Answers2

2

If you are using express and want to render HTML files you should use ejs as your template engine. Here is how you do it from scratch:

start a new project with express -e

tell express to use ejs for rendering HTML files:

app.configure(function(){
  // ... 
  app.set('views', __dirname + '/views');
  // app.set('view engine', 'ejs');
  app.engine('html', require('ejs').renderFile);
  // ...
});

create a route:

app.get("/", function(req, res) {
  res.render("your.html", {
    title: "This is plain HTML rendered with ejs"
  })
})

and finally your your.html file in the views folder

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>
zemirco
  • 16,171
  • 8
  • 62
  • 96
0

It sounds like you want to use templates, here is an example:

https://github.com/chovy/express-template-demo

chovy
  • 72,281
  • 52
  • 227
  • 295