2017-08-31 70 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 
相关问题