Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables to Jade without Express

Quick question about the Jade template engine:

  • How can you pass 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?

like image 464
m_vdbeek Avatar asked Sep 07 '12 16:09

m_vdbeek


2 Answers

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.

Simple Example

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>


Using Jade Options

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>
like image 24
Zanon Avatar answered Oct 12 '22 00:10

Zanon


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}
like image 127
Vadim Baryshev Avatar answered Oct 12 '22 02:10

Vadim Baryshev