besabestin
besabestin

Reputation: 492

Do I only have to use a templating language with express render?

I am learning node and express from the simplest and when rendering views using res.render('view',{data:data}) is it only a template engine like jade that fits in view. can I not use a normal html?

Upvotes: 1

Views: 173

Answers (2)

esp
esp

Reputation: 7687

The great thing about Node is that it forces you to separate templates from logic (to a certain level, you can squeeze a lot of logic into template anyway).

I didn't like Jade and used EJS until it turned out that client-side EJS is different from server-side and you cannot really re-use templates in the browser (as you would definitely want at some point, when you start rendering pages in the browser). You can re-use simple EJS templates but you cannot re-use templates with partials (as most of your templates will be).

After a lot of searching and trial-and-error I ended up using doT templates that are very fast (the fastest there is, actually), light-weight (only 140 lines of JavaScript), can be easily integrated in Express (by following the pattern of consolidate - you can't use consolidate directly with doT yet), can be used in the browser (the function to load partials will have to be different, but it is easy again).

doT seems to have features that I haven't seen in other templating engines, has a very elegant syntax that is the closest to handlebars (my favourite) but still allows normal JavaScript inside (that's why I chose EJS in the first place).

Upvotes: 0

L0j1k
L0j1k

Reputation: 12635

You can, but this is a problem I ran into when I was learning Node. If you do not want to use a templating engine, you can still have Node just spit out the contents of your HTML file in a static way. For example (VERY BASIC EXAMLE):

var base = '/path/to/your/public_html',
  fs = require('fs'),
  http = require('http'),
  sys = requrie('sys');

http.createServer(function (req,res) {
  path = base + req.url;
  console.log(path);

  path.exists(path, function(exists) {
    if(!exists) {
      res.writeHead(404);
      res.write('Bad request: 404\n');
      res.end();
    } else {
      res.setHeader('Content-Type','text/html');
      res.statusCode = 200;
      var file = fs.createReadStream(path);
      file.on("open",function() {
        file.pipe(res);
      });
      file.on("error",function(err) {
        console.log(err);
      });
    }
  });
}).listen(80);

console.log('server on tcp/80');

Upvotes: 1

Related Questions