【问题标题】:Render array in Jade在 Jade 中渲染数组
【发布时间】:2014-11-10 18:52:54
【问题描述】:

我把一个数组传给了jade

router.get('/index', function(req, res){
    var users = ["A","B","C"];  
    res.render('index', {user: users})
});   

//我在翡翠中得到了什么

li #{user}
<li>a,b,c</li>                               

li #(user[0])
<li>a</li>

我怎样才能得到这个而不用写 user[0], user[1], user[2]?

<li>A</li> 
<li>B</li> 
<li>C</li>

我已尝试关注,但我有错误。

#{user}中的每个项目
用户中的每个项目

【问题讨论】:

    标签: javascript arrays node.js pug


    【解决方案1】:

    使用each(see docs)

    ul
      each user in users
        li= user
    

    您应该将渲染调用更改为:

    res.render('index', {users: users})
    //                       ^ added this character
    

    由于您有一个user 对象数组,因此您应该将其命名为users。这样您就可以将user(单数)映射到每个用户的价值。

    【讨论】:

    • 嗨,我收到错误“无法读取未定义的属性'长度'”。用户未定义
    • 查看我的编辑。显然你需要引用你传递给模板的变量。
    【解决方案2】:

    有关文档,请参阅 here

    ul                     // create ul list tag
      each u in user       // start loop
        li= u              // create li tag and assign innerHTML to array item value
    

    【讨论】:

    • 嗨,我收到错误“无法读取未定义的属性'长度'”。用户未定义
    • 我更新了答案。你的视图有user,而不是users
    【解决方案3】:

    如果数组不太适合原生数组,您也可以使用 javascript(已作为答案发布)。 - for (var i = 0; i < users.length; ++i) { li= users[i] - }

    见:Loop in Jade (currently known as "Pug") template engine

    【讨论】:

    • 你的循环在 1..10 在很多情况下会抛出一个越界异常。
    猜你喜欢
    • 2017-06-10
    • 2016-12-17
    • 2014-01-15
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2017-10-20
    • 2013-04-15
    • 1970-01-01
    相关资源
    最近更新 更多