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 ?
Asked
Active
Viewed 1.8k times
4 Answers
26
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>

xavier.seignard
- 11,254
- 13
- 51
- 75
-
You can use [app.render](http://expressjs.com/api.html#app.render) to render a template to a string, as mentioned in [this](http://stackoverflow.com/questions/15403791/in-express-js-app-render-vs-res-render-whats-the-difference#answer-15404507) more recent answer. – Dan Ross Sep 04 '13 at 17:03
13
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!

Ilya Rogojin
- 321
- 2
- 11
6
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);

Nocturno
- 9,579
- 5
- 31
- 39
-
1Correct. Here is a relevant question regarding how to check for errors: http://stackoverflow.com/questions/7283896/how-can-i-catch-a-rendering-error-missing-template-in-node-js-using-express-js/34709515#34709515 – Wtower Jan 10 '16 at 18:59
-
which jade version is that? my renderFile (v1.2.0) expects 3 arguments – akcasoy Jan 27 '16 at 17:59
-
@akcasoy These are the most current docs: http://jade-lang.com/api/. The `renderFile()` description is at the very bottom and shows 2 arguments are required. – Nocturno Jan 27 '16 at 18:50