Quick question about the Jade template engine:
node.js
variables to a .jade
template when you're not using express.js
?I'm trying to make a small website that doesn't use express, just so that I can understand how everything works.
Also, are there tutorials or articles about the use of Jade and node.js
without express?
Vadim's answer is nice, but old. It uses a different syntax to declare Jade variables then what is used currently at Jade's official tutorial. Also, it does not show how to use Jade options.
index.jade
doctype html
html
head
title= pageTitle
body
h1= greetings
In this example, variables are pageTitle and greetings.
app.js
var jade = require('jade');
var locals = {
pageTitle : 'My Page',
greetings : 'Hello World!'
};
jade.renderFile('index.jade', locals, function(err, html) {
console.log(html);
});
Output:
<!DOCTYPE html><html><head><title>My Page</title></head><body><h1>Hello World!</h1></body></html>
The previous example outputs the HTML without pretty print. That's not a problem, but Jade has an option that outputs pretty printed HTML. You can see the full list of options here.
Jade's official tutorial doesn't teach how to use options when you also have variables in your template. Jade's GitHub page tries to teach, but is incomplete. It uses:
jade.renderFile('filename.jade', merge(options, locals));
As merge
is an undefined function, you have to define it. This function will merge two JSON objects.
app.js
var jade = require('jade');
function merge(obj1, obj2) {
var result = {};
for(var key in obj1)
result[key] = obj1[key];
for(var key in obj2)
result[key] = obj2[key];
return result;
}
var options = {
pretty : true
};
var locals = {
pageTitle : 'My Page',
greetings : 'Hello World!'
};
jade.renderFile('index.jade', merge(options, locals), function(err, html) {
console.log(html);
});
Output:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
var jade = require('jade');
jade.renderFile('tpl.jade', { hello: 'world' }, function(err, html) {
console.log(err);
console.log(html);
});
tpl.jade:
html
body
h1 #{hello}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With