Sails.js - passing data to a view

我与影子孤独终老i 提交于 2019-12-04 17:56:17

问题


I've recently started learning how to use Sails.js and I came across a small issue.

I have a model called Applicant, as follows:

module.exports = {

  attributes: {     
     name: {
      type: 'STRING',
      required: true
     },

     email: {
      type: 'STRING',
      required: true
     }

  }

};

I have built the index action to return all the instances of the Applicant model:

module.exports = {
    index: function(req, res) {
        Applicant.findAll().done(function(err, applicants) {
            res.view({
                apps: applicants
            });
        });
    }
};

And this is the view that I am using:

<section id="applicants">
    <h1>List of applicants</h1>

    <ul>
        <% for (applicant in apps) { %>
        <li><%= applicant.name %> <%= applicant.email %></li>
        <% } %>
    </ul>
</section>

Still, when I load the corresponding URL, I can't see my data displayed.

I have read the Sails.js documentation, but I can't seem to find what's wrong with my code.

It would be great if someone could help me solve this problem.

Thank you!


回答1:


Try

<%= apps[applicant].name %>

It's just like for loop works. applicant is an index in apps array.

Edit: Better way is to use javascript array's built in method forEach, because this way you avoid cycling through elements, inherited from apps's type (for example, elements, assigned like this: apps.__proto__.foo = {name: "bar"} or Array.prototype.foo2 = {name: "pi222"}).

<% apps.forEach(function(applicant)  { %>
    <li><%= applicant.name %> <%= applicant.email %></li>
<% }); %>

P.S. Of course this javascript's method (forEach) wouldn't work in IE <= 8(if you consider to use it in browser). But we are inside NodeJs, which is built on top of V8 engine. So this will work, anyway.



来源:https://stackoverflow.com/questions/18229908/sails-js-passing-data-to-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!