首页 > 解决方案 > 在服务器端使用 express-handlebars 在 node.js 上显示字符串集合

问题描述

我有要使用 express-handlebars 显示的 sql 查询结果

var x={} ;

//friends表得到了name|profileName|status属性

 dao.findFriends(req.session.UserName,function(err,rows,fields){
    x=rows;
    for(var i=0;i<rows.length;i++){
        console.log(rows[i].profileName);   
    }
});

res.render('home',{body:'hello ...'+req.session.UserName,friends:x});

简单的字符串显示正常,但不是 sql 结果

<table>
    <tr>
      <th>Name</th>

    </tr>
    {{#each friends}}
    <tr>
      <td>{{profileName}}</td>

    </tr>
    {{/each}}
  </table>

标签: mysqlnode.jsexpress-handlebars

解决方案


找到了!必须使变量x接受 json 数组和 .. 并将所有结果推入x内 for 循环

var x =[];
dao.findFriends(req.session.UserName,function(err,rows,fields){
            if(!err){
            console.log('listing friends');
            //list in bunch of <li> <ul> </ul>
                for(var i=0;i<rows.length;i++){
                    console.log(rows[i].profileName);
                    //x = rows;
                    x.push({
                                    profileName: rows[i].profileName
                                });
                    }
                }
                else
                console.log('err finding people...');
                res.render('home',{body:'hello ...'+req.session.UserName,friends:x});
            });

并在 html 端引用具有前缀的字段

<table>
<tr>
  <th>Name</th>

</tr>
{{#each friends}}
<tr>
  <td>{{this.profileName}}</td>

</tr>
{{/each}}


推荐阅读