How do I pass variable from a Jade template file to a Javascript file?

How do I pass variable from a Jade template file to a Javascript file?

Problem

Im very new to Node.js and trying to get my head round few things.How do I pass variable from a Jade template file to a JS file?

I have got this line of code in my server.js file

res.render("aws.jade", {data : JSON.stringify({'val' : 'This is a Test'})});

Basically Im just trying to get values in data to aws.jade template file

And this is aws.jade

html
    head
       script(type='text/javascript')
            var data = !{data}
        link(rel='stylesheet', href='/stylesheets/style.css')
    body
        title Title
        h1 Heading
        #div.test

I keep getting this error in the Firebug console:

<var>data = {"val":"This is a Test"}</var>

Could someone please explain as to why this is happening and a way for me to pass variable from a Jade template file to a JS file?

Thank You

Problem courtesy of: manraj82

Solution

Try adding a . character after the script, this tells Jade that you want a block of text inside a tag.

Here’s your updated code.

html
    head
        script(type='text/javascript').
            var data = !{data}
        link(rel='stylesheet', href='/stylesheets/style.css')
    body
        title Title
        h1 Heading
        #div.test

EDIT – To set title to data.val

First you should change your response, remove JSON.stringify so you’re returning an object not a string value.

res.render("aws.jade", {data : {'val' : 'This is a Test'}});

Then you should be able to access the data objects attributes and structure directly using dot notation, and assign it straight to the title element like this…

title= data.val
Solution courtesy of: Jonathan Miles

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *