簡體   English   中英

如何將數據數組從express.js傳遞到ejs模板並呈現它們

[英]How to pass a data array from express.js to ejs template and render them

我在我的nodejs Web應用程序中使用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模板語言來呈現數組中的所有對象。 如何將數據傳遞到模板並進行渲染?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM