Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile jade template file to get string?

Tags:

node.js

pug

I have a view logic in my jade template file. How can I pass model in to jade and get html for further sending by email ?

like image 584
Oleg Dats Avatar asked Nov 13 '12 14:11

Oleg Dats


4 Answers

You can try the following:

var jade = require('jade'),
    fs = require('fs');

fs.readFile('template.jade', 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);
    var fn = jade.compile(data);
    var html = fn({name:'Oleg'});
    console.log(html);
});

Where template.jade is the path to your template. And it look like this:

!!!
html
  head
    title= 'Hello world'
  body
    p Hello #{name}!

So you pass your model as input of the fn() function, and the output of it will be the html.

<!DOCTYPE html><html><head><title>Hello world</title></head><body><p>Hello Oleg!</p></body></html>
like image 73
xavier.seignard Avatar answered Oct 05 '22 12:10

xavier.seignard


Also you can catch the string from render callback (express example)

exports.test1 = function(req, res){
  res.render('test1', { title: 'test1' }, function(err, body) {
    console.log(body);
  });

  res.send('wooo');
};

test1.jade

div
  = title
p hello world!
like image 36
Ilya Rogojin Avatar answered Oct 05 '22 11:10

Ilya Rogojin


Opening the template with fs.readFile() is no longer necessary. The Jade API includes the compileFile() method that compiles directly from a file.

var jade = require("jade");

var locals = {name: "Linus"},
    render = jade.compileFile('template.jade'),
    html   = render(locals);

The Jade API also includes the renderFile() method that directly returns an html string from a given file, making it even simpler.

var jade = require("jade");

var locals = {name: "Linus"},
    html   = jade.renderFile('template.jade', locals);
like image 42
Nocturno Avatar answered Oct 05 '22 10:10

Nocturno


The answers all work for loading the jade template and compiling it to HTML using locals. However if you are sending HTML emails you need to be aware that most clients strip out all CSS classes. Use Juice (or something like it) to apply all of the CSS classes inline.

like image 23
Cade Daniel Avatar answered Oct 05 '22 11:10

Cade Daniel