简体   繁体   中英

How can I let scripts span multiple lines in Jade?

Right now, I have this in a navigation view partial:

script.
    links = [
        {title: 'Dashboard', url: '/'},
        { title: 'Users', sublinks: [
                {title: 'Manage', url: '/users'}
            ] }
    ]
ul.nano-content
    - each link in links
        li
            a(href="#")= link.title

But Jade is complaining, I'm getting this error:

Cannot read property 'length' of undefined

and it is pointing to - each link in links . This works when I put everything on one line, but it's ugly and is tough to read/maintain, how can I make it possible to span multiple lines like I have it?

You're mixing two pieces of JavaScript - in-browser code you keep in between <script> tags, and backend JS. Contents of script. ( <script/> tag) aren't bound to variables used in Jade template - so links in this line:

    - each link in links

is undefined - a direct cause of your error.

Solution depends on how you compile Jade template. Compilation is a process when as input you put both template itself and some data which will be bound to variables inside of template (ie links variable), and as an output you get HTML.

For instance, if you're serving it dynamically from Node.js backend, assuming you're using Express.js, you might want to define route similar to:

app.get('/', function (req, res) {
    // .render() will take template named "index",
    // and a map with "links" property, and use it
    // to generate output HTML document.
    // Each key from the map will be bound at the template
    // level, so you'll be able to use it there.
    res.render('index', {links: [
        {title: 'Dashboard', url: '/'},
        { title: 'Users', sublinks: [
            {title: 'Manage', url: '/users'}
        ]}
    ]});
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM