如何让脚本在Jade中跨越多行?

How can I let scripts span multiple lines in Jade?

本文关键字:跨越 Jade 脚本      更新时间:2023-09-26

现在,我在导航视图中设置了这个部分:

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

但是Jade在抱怨,我得到这个错误:

Cannot read property 'length' of undefined

,指向- each link in links。当我把所有东西放在一行上时,这是有效的,但它很难看,很难阅读/维护,我怎么能让它像我一样跨越多行呢?

你在<script>标签和后端JS之间混合了两段JavaScript -浏览器内代码。script. (<script/>标签)的内容不绑定到Jade模板中使用的变量-所以links在这一行:

    - each link in links

未定义,这是导致错误的直接原因。

解决方案取决于您如何编译Jade模板。编译是一个过程,当你把模板本身和一些数据作为输入,这些数据将被绑定到模板内部的变量(即links变量),作为输出你得到HTML。

例如,如果你从Node.js后端动态地提供它,假设你使用Express.js,你可能想要定义类似于:

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'}
        ]}
    ]});
})