res.render, res.write and Jade

res.render, res.write and Jade

Problem

I’m trying to make simple ftp client in Node.js. Everything works fine, but I don’t know how to write “singleFile.name” in my Jade template.

app.post('/ftp/login', function(req, res){
  ftp.ls("/directory", function(err, files){
      if (err) return console.error(err);

      files.forEach(function(singleFile) {
        if (singleFile != null){
        console.log(singleFile.name + "<br>");
        }
      });
  });

 res.render('ftpLogin', { host: fHost, username: fUsername, port: fPort});
});

There’s no problem without “res.render”, but i want add it into my template.

res.writeHead(200, {"Content-type" : "text/html; charset=utf-8"});
[...]
res.write(singleFile.name + "<br>");
[...]
res.end();

I’m newbie (3 days Node learning), so I will be glad for all your responses to mistakes.

Thank you!

Problem courtesy of: Johnny Drag’n Drop

Solution

It would be best to send the files array to the Jade template.

res.render('ftpLogin', { host: fHost, ..., files: files });

Then write a loop in the template. For example:

each file in files
    | #{file.name}
    br

See the Jade loops documentation: https://github.com/visionmedia/jade#a9

It’s not really good practice to try to ‘pre-format’ your code with things like + "<br>" since that, itself, is the point of a template engine.

Solution courtesy of: Bret Copeland

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *