2
votes

I've read and re-read the jade references and a whole bunch of stack overflow questions but I can't seem to figure this out and I think it should be really simple.

So all I want to do is have an object in a JavaScript file, and have that imported into my jade file so I can use the data from the object when generating my html page.

for example:

This would be in a JS file:

 var obj = {
  firstName: "bob",
  lastName: "smith",
  age: 109

};

And in my jade I want to do this:

h1 #{obj.firstName}, #{obj.lastName}
h2= obj.age

etc.

This is just a simple example. Any help at all would be much appreciated.

I would simply create the object in my jade but I want the object to be formatted where each item is on its own line (for readability), and jade doesn't currently support that.

On that link someone mentioned a solution that I did not understand at all: "so I accomplished what I wanted by passing in the array in grunt-contrib-jade instead of putting it directly in the template. Also allowed me to get rid of grunt-sed"

I am using codekit to compile my jade into static html, not Node.JS.

1
How would I pass the object into my jade file? All I want is to have data stored in an object that I can use in my jade file. This works automatically with jade with one small problem, the object has to be on one line. It would be written like this: -var obj = {firstName: "bob", lastName: "smith"}; but I need it to be on multiple lines like I showed above, so I was told I could have the object in a separate javascript file, instead of directly in my jade file. But I don't know how to make that work.d3ddd
Did you ever figure out how to do this? :suser5102448

1 Answers

1
votes

This can be accomplished if you translate your object to JSON format.

From the docs on command line arguments:
-O, --obj <path|str> JavaScript options object or JSON file containing it

Example:

user.json

{
  "firstName": "bob",
  "lastName": "smith",
  "age": 109
}

And you would compile your template like that:

$ jade myTemplate.jade --obj user.json

or if you're using Gulp with gulp-jade:

.pipe(jade({
  locals: require('user.json')
}))