2017-08-31 66 views
0

我在網上的NodeJS應用程序,用戶輸入一些條件使用express.js和程序獲取數據的數組像這樣:如何從express.js數據數組傳遞給EJS模板,並將其呈現

var data = [ 
    { 
    name: 'Salmons Creek', 
    image: 'https://farm6.staticflickr.com/5479/11694969344_42dff96680.jpg', 
    description: "Great place to go fishin' Bacon ipsum dolor amet kielbasa cow" 
    }, 
    { 
    name: 'Granite Hills', 
    image: 'https://farm5.staticflickr.com/4103/5088123249_5f24c3202c.jpg', 
    description: "It's just a hill. Made of granite. Nothing more! Cow doner." 
    }, 
    { 
    name: 'Wildwood Miew', 
    image: 'https://farm5.staticflickr.com/4016/4369518024_0f64300987.jpg', 
    description: 'All campsites. All the time.Short ribs pastrami drumstick.' 
    }, 
    { 
    name: 'Lake Fooey', 
    image: 'https://farm7.staticflickr.com/6138/6042439726_9efecf8348.jpg', 
    description: 'Hills and lakes and lakes and hills. Pork ribeye pork chop.' 
    } 
]; 

我想使用EJS模板語言來渲染數組中的所有對象。我如何將數據傳遞給模板並渲染它們?

+0

使它們究竟如何?就像一個字符串,在元素中?你必須給我們一個你想要的輸出的例子 – adeneo

+1

[用EJS模板傳遞變量]的可能重複(https://stackoverflow.com/questions/25596615/passing-variable-with-ejs-templating) –

+0

大多數模板引擎具有所謂的上下文。在ejs中,它是渲染方法的第二個參數。所以你應該做一些像'res.render('page1',{data:data})'這些數據應該可以用於你的EJS腳本。 – Keith

回答

2

在您的JS文件,你應該呈現這樣的EJS:

var express = require('express'); 
var app = express(); 
var path = require('path'); 

// viewed at http://localhost:8080 
app.use("/", express.static(__dirname + '/')); 
app.set('view engine', 'ejs'); 
app.get('/', function(req, res) { 
var data = [ 
{ 
    name: 'Salmons Creek', 
    image: 'https://farm6.staticflickr.com/5479/11694969344_42dff96680.jpg', 
    description: "Great place to go fishin' Bacon ipsum dolor amet kielbasa cow" 
    }, 
{ 
    name: 'Granite Hills', 
    image: 'https://farm5.staticflickr.com/4103/5088123249_5f24c3202c.jpg', 
    description: "It's just a hill. Made of granite. Nothing more! Cow doner." 
    }, 
{ 
    name: 'Wildwood Miew', 
    image: 'https://farm5.staticflickr.com/4016/4369518024_0f64300987.jpg', 
    description: 'All campsites. All the time.Short ribs pastrami drumstick.' 
    }, 
{ 
    name: 'Lake Fooey', 
    image: 'https://farm7.staticflickr.com/6138/6042439726_9efecf8348.jpg', 
    description: 'Hills and lakes and lakes and hills. Pork ribeye pork chop.' 
    } 
]; 
res.render('index.ejs', {data:data}); 
}); 

app.listen(8080); 

而在你EJS文件,您可以呈現這樣的數據變量:

<!DOCTYPE html> 
<html> 

<head> 
    <meta charset="utf-8"> 
</head> 

<body> 
    <ul> 
    <% data.forEach(function(dat) { %> 
     <li><%= dat.name %></li> 
     <li><%= dat.image%></li> 
     <li><%= dat.description%></li> 
    <% }); %> 
    </ul> 
</body> 

</html> 

我已經嘗試過了,它作品。

的文件夾結構是這樣的:

. 
+-- app.js 
+-- views 
| +-- index.js 
相關問題