express+jade: provided local variable is undefined in view (node.js + express + jade)

Question!

I'm implementing a webapp using node.js and express, using the jade template engine.

Templates render fine, and can access helpers and dynamic helpers, but not local variables other than the "body" local variable, which is provided by express and is available and defined in my layout.jade.

This is some of the code:

app.set ('view engine', 'jade');

app.get ("/test", function (req, res) {  
    res.render ('test', {
        locals: { name: "jake" }
    });
});

and this is test.jade:

p hello
=name

when I remove the second line (referencing name), the template renders correctly, showing the word "hello" in the web page. When I include the =name, it throws a ReferenceError:

500 ReferenceError: Jade:2 NaN. 'p hello' NaN. '=name' name is not defined
NaN. 'p hello'
NaN. '=name'

I believe I'm following the jade and express examples exactly with respect to local variables. Am I doing something wrong, or could this be a bug in express or jade?

By : Jake


Answers

I think the error is sometime caused due to the request by the browser for favicon.ico.

Try adding these lines to the layout.jade head to link the icon

link(rel='icon', href='/images/siteicon.png')

This removed the same error that I was getting

By : slv007


Rather than =, you can use #{variable-name}. Here is an example of how I'm using it: This will render a page, with a menu for navigation. Passing the page title in each time the page is loaded, ofcourse you will need to create an app.get function for each page.

App.js

var navigation = {
  home : {
    uri : "/",
    url : "index",
    title : "Home"
  },
  lab : {
    uri : "/lab",
    url : "lab",
    title : "Lab"
  },
  profile : {
    uri : "/profile",
    url : "profile",
    title : "Profile"
  },
  timetable : {
    uri : "/timetable",
    url : "timetable",
    title : "Timetable"
  }
}

app.get(navigation.profile.uri, function(req, res){ //Profile
  res.render(navigation.profile.url, {
    title: navigation.profile.title,
    navigation: navigation
  });
});

profile.jade

section#page-content
  h1#page-title #{title}
  p Welcome to #{title}

layout.jade

!!! 5
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/reset.css')
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    header#site-header
      nav#site-navigation
        != partial("partials/navigation")
    section!= body
  footer#page-footer
By : Jack


app.set ('view engine', 'jade');

app.get ("/test", function (req, res) {  
    res.render ('test', {
        name: "jake"
    });
});

you can do it like this.

By : arden


This video can help you solving your question :)
By: admin