Sails.js - 将数据传递给视图 [英] Sails.js - passing data to a view

查看:127
本文介绍了Sails.js - 将数据传递给视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习如何使用Sails.js,我遇到了一个小问题。

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

我有一个名为Applicant的模型,如下所示:

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>

但是,当我加载相应的URL时,我看不到我的数据显示。

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

我已经阅读了Sails.js文档,但我似乎无法找到我的代码有什么问题。

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.

谢谢!

推荐答案

尝试

<%= apps[applicant].name %>

就像 循环一样。 申请人 apps 数组中的索引。

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

编辑:更好的方法是使用javascript数组的内置方法 forEach ,因为这样可以避免循环使用继承自的元素apps 的类型(例如,元素,分配如下: apps .__ proto__.foo = {name:bar} Array.prototype.foo2 = {name:pi222} )。

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。当然这个javascript的方法( forEach )在IE< = 8中不起作用(如果你考虑在浏览器中使用它)。 但是我们在NodeJs里面,它建立在V8引擎之上。无论如何,这将有效。

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.

这篇关于Sails.js - 将数据传递给视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆