LawrenceH
LawrenceH

Reputation: 385

using jQuery with Jade

I'm current developing a web app that uses Jade as the template engine and passing data to Jade with Express.

Say I have the variable "book" to pass

res.render('book_detail',{book: book});

I want to access the details inside the book such as book.author, book.pages, etc with jQuery (my frontend jQuery lives inside an external main.js file) instead of doing it with Jade. How can I achieve this?

I have already tried all kinds of method as suggested by others like var myBook = !{JSON.stringify(book)} or make it a javascript variable with the script. syntax in Jade and I can't even do a console.log with an output!

Please kindly help me on this as I have been stuck with these for the whole day and seems sharing a express variable between Jade and jQuery (Javascript) is so hard to achieve...

Upvotes: 2

Views: 6500

Answers (2)

JNevens
JNevens

Reputation: 11982

In your Jade file, you can put:

script.
    var book = '#{book}'
script(src='someFile.js')

Now, inside someFile.js, you can use book like a normal variable:

$(document).ready( function() {
    console.log(book.title);
});

Upvotes: 7

zuo
zuo

Reputation: 1091

Try sth like

- var j = 'var book = '+JSON.stringify(book)
script !{j}

and window.book will be available on client side.

Upvotes: 0

Related Questions