如何将数据数组从express.js传递到ejs模板并进行渲染

时间:2017-08-31 13:47:11

标签: javascript node.js express ejs

我在我的nodejs web app中使用express.js,用户输入了一些条件,程序得到了一个数据数组,如下所示:

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模板语言来渲染数组中的所有对象。如何将数据传递给模板并渲染它们?

1 个答案:

答案 0 :(得分:3)

在你的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