如何遍历对象内部的数组(把手)

时间:2018-09-27 22:16:12

标签: javascript node.js express handlebars.js express-handlebars

我试图遍历作为对象一部分的数组。

下面是我的用户架构

var UserSchema = new Schema({
    username: String,
    email: String,
    password: String,
    company: String,
    contact: Number,
    country: String,
    isLoggedIn: Boolean,
    createdOn: { type: Date, default: Date.now },
    ads: [{ type: Schema.Types.ObjectId, ref: 'Ad' }],
    notification: {
        counter: {type: Number, default: 0},
        notidata: [{
            itemdate: { type: Date, default: Date.now },
            data: {
                heading: String,
                para: String
            },
            read: {type: Boolean, default: false}
        }]
    }
});

比方说,数据库中有两个notidata(数组元素[0]和[1])。 在这种情况下,我尝试打印所有在数据库中的两个notidata。

这是我的观点

 <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav ml-auto">

            <li class="nav-item dropdown ">
                {{#each session.user.notification.notidata.[0]}}
                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
                    <a href="/users" class=" dropdown-item list-group-item-action flex-column align-items-start">
                        <div class="d-flex w-100 justify-content-between">
                            <h6 class="mb-1">{{data.heading}}</h6>
                        </div>
                        <p class="mb-1">{{data.para}}</p>
                    </a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="#">View All</a>
                </div>
                {{/each}}
            </li> 

我得到的1 div下拉列表太空了。首先,为什么要打印一个div,因为notification.notidata中有两个元素;其次,为什么{{data.heading}}和{{data.para}}没有被打印。多谢帮助! :)

2 个答案:

答案 0 :(得分:0)

{{#each session.user.notification.notidata.[0]}}更改为:{{#each session.user.notification.notidata}}在我创建的用于模拟Web应用程序设置的示例Web应用程序上工作。为了简单起见,我模拟了一个会话对象:(从您的UserSchema和示例notidata数组中),并创建了一个简单的车把模板,其中包含使用所需的 data.properties(para和标题)在这种情况下,HTML无关紧要,因为它可能是任何东西,重点只是表明{{#each}} handlebarjs注释在模板中按预期方式工作。我怀疑问题出在您的通知数组,出于某种原因,此数组仅包含1个元素。下面粘贴的是示例Web应用程序的相关文件,要查看整个示例项目,请查看此处:https://github.com/nathanwright1242/handlebarTest

Index.html 注意handlebarjs模板挂钩: handlebarsTmpl

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">    
  <title>Handlebarjs Templating example</title>
  <meta name="description" content="The HTML5 Herald">
  <meta name="author" content="SitePoint">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
  <div id='handlebarHook'></div>
</head>

<body>

  <script id="handlebarsTmpl" type="text/template">
   <div>
        {{#each session.user.notification.notidata}}
        <ul class="list-group">
            <li class="list-group-item">{{data.heading}}</li>
            <li class="list-group-item">{{data.para}}</li>
       </ul>
       {{/each}}
   </div>
  </script>

  <!-- bootstrap4 dependencies -->
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
  <!-- backbonejs dependencies -->
  <script src='js/lib/underscore-min.js'></script>
  <script src='js/lib/backbone-min.js'></script>
  <!-- handlebarsjs -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
  <!-- normal app separation -->
  <script src='js/views/HandleBarView.js'></script>
  <script src='js/app.js'></script> 

</body>
</html>

HandleBarView.js 将使用来自会话对象的动态数据填充车把模板的视图

var app = app || {}

app.HandleBarView = Backbone.View.extend({
    el: '#handlebarHook',
    template: $('#handlebarsTmpl').html(),
    initialize: function(notidata){
        this.notidata = notidata;
        this.render();
    },
    render: function(){
        let templateScript = Handlebars.compile(this.template);
        this.$el.html(templateScript( this.notidata ));
        return this;
    }
});

app.js Web应用程序中的入口,传入会话对象:与您的模式和示例数据模拟相同

  var app = app || {};

$(function() {
let data = {
    session: {
        user: {}
    }
};
data.session.user = {
    'username': 'testuser',
    'email': 'test@gmail.com',
    'password': 'password',
    'company': 'myCompany',
    'contact': 1234,
    'country': 'United States',
    'isLoggedIn': true,
    'createdOn': '2018-09-27T22:59:41.655Z',
    'ads': [],
    'notification': {
        'counter': 1,
        'notidata': [ 
            { data: { heading: 'Welcome edited', para: 'MaujouharatMarketPlace welcomes you!' }, read: false, itemdate: '2018-09-27T22:59:41.655Z' }, 
            { data: { heading: 'This is second notification', para: 'yes man' }, read: false, itemdate: '2018-09-27T22:59:41.655Z' } 
        ] 
    }
};
    new app.HandleBarView(data);
});

结果: (通过查看项目的索引文件进行代码验证)

result

答案 1 :(得分:0)

我已经尝试过

 {{#each session.user.notification.notidata}}

                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">

                        <a href="/users" class=" dropdown-item list-group-item-action flex-column align-items-start">
                            <div class="d-flex w-100 justify-content-between">

                                <small>heading -> {{data.heading}}</small>


                            </div>
                            <p class="mb-1"></p>
                            <small></small>
                        </a>


                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#">View All</a>
                    </div>
                    {{/each}}

它将仅打印一个元素。甚至当我打印{{session.user.notification.notidata}}时,我都认为是Object对象,所以Object对象是正确的,因为notidata数组中有两个元素。

这是数据库的外观

{
   "_id":"5bad3c53967c040c3c86c504",
   "notification":{
      "counter":1,
      "notidata":[
         {
            "data":{
               "heading":"second"
            }
         },
         {
            "data":{
               "heading":"third"
            }
         }
      ]
   },
   "ads":[

   ],
   "username":"rghe",
   "email":"gbngt@dc.com",
   "password":"dfg",
   "country":"AUS",
   "createdOn":"2018-09-27T20:23:47.820Z",
   "__v":0
}