[英]Iteration of arrays and objects in handlebars
Schema.js
var ItemSchema = mongoose.Schema({
username: {
type: String,
index: true
},
path: {
type: String
},
originalname: {
type: String
}
});
var Item = module.exports = mongoose.model('Item',ItemSchema, 'iteminfo');
route.js
router.get('/', ensureAuthenticated, function(req, res){
Item.find({},function(err, docs){
res.render('welcome', {docs:docs});
});
});
index.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
[list of data here!!!]
</body>
</html>
我的路線代碼是否正確? 如何在index.js
顯示所有數據? 請幫助。 我是node.js
和mongoDB
的新手。 謝謝 :)
在mongo shell中,當我點擊db.users.find()
,它有兩個集合。 我希望所需的輸出在索引中像這樣
username = "username1"
path = "path1"
originalname = "originalname1"
username = "username2"
path = "path2"
originalname = "originalname2"
可能嗎? 喜歡做一些foreach
概念。
在.hbs文件中
您可以使用內置的每個幫助程序迭代列表。 在塊內,您可以使用它來引用正在迭代的元素。
<ul class="people_list">
{{#each docs}}
<li>{{this}}</li>
{{/each}}
</ul>
以及包含數組內對象的docs
[{}, {}, {}]
<ul class="people_list">
{{#each docs}} // iterating over array, and #each below loops the properties of elements {}
<li> {{#each this}} </li>
{{this}} // references the property values
{{/each}}
{{/each}}
</ul>
文件就在這里
讓我們考慮一下你的模型中有2個字段。 名稱和_id。 您需要將其呈現給視圖。
在這里你需要'ejs'模塊,一個用於在html中呈現數據的模板框架。
Server.js
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
將所有視圖保留在“父文件夾/視圖”中。
routes.js
router.get('/', ensureAuthenticated, function(req, res){
Item.find({},function(err, docs){
res.render('welcome', {docs:docs}); // here the welcome should be the file name of the html you need to render
});
});
welcome.html
<table>
<% for(var i=0; i < docs.length; i++) { %>
<tr>
<td><%= docs[i].id %></td>
<td><%= docs[i].name %></td>
</tr>
<% } %>
</table>
這是ejs的語法。
您的示例輸出將是這樣的
<table>
<tr>
<td>1</td>
<td>bob</td>
</tr>
<tr>
<td>2</td>
<td>john</td>
</tr>
<tr>
<td>3</td>
<td>jake</td>
</tr>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.