使用循环的节点js和ejs

时间:2018-10-31 21:50:31

标签: javascript node.js loops express ejs

我是node.js的新手,现在我遇到了EJS模板的问题。我注意到我的for循环虽然没有通过EJS模板运行。我试图制作一个非常基本的待办事项应用程序。

这是我所做的项目的层次结构

This is my project hierarchy

这是我的App js模块

let express = require('express');
let todoController = require('./Controller/todoController')
let app = express()
app.set('view engine', 'ejs');
todoController(app);




app.listen(3000,function(){
console.log('server started on http://localhost:3000');
})

todoController.js

 let toDoList = ['Go to university','Smoking sigrate'];
    module.exports= function(app){
        app.get('/', function(req, res){
            res.render('index.ejs', {toDoList: toDoList});
        });

        app.get ("*", function(req,res){
            res.send("<h1>Invalid page</h1>");
        })
    }

index.ejs

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Todo</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
    crossorigin="anonymous">

</head>

<body>


  <!-- As a heading -->
  <nav class="navbar navbar-light bg-dark">
    <span class="navbar-brand mb-0 h1 text-white">Todo List</span>
  </nav>
  <br><br>
  <div class="container">
    <form>
      <div class="form-group text-white bg-dark">
        <label for="formGroupExampleInput2">Enter to do item</label>
        <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Input a item to do list....">
        <input type="submit" class="form-control bg-primary text-white h3" >
      </div>
    </form>
  </div>

  <br><br>
    <div class="row">
    <ul class="col-6 mx-auto" >

      <% for(let i =0; toDoList.length; i++){ %>
        <li> <%= toDoList[i] %> </li>
      <% } %>

    </ul>
  </div>

</body>

</html>

2 个答案:

答案 0 :(得分:0)

<% for(let i =0; i<toDoList.length; i++){ %>
    <li> <%= toDoList[i] %> </li>
  <% } %>

使用i

答案 1 :(得分:0)

您缺少循环条件

      <% for(let i =0;i < toDoList.length; i++){ %>
        <li> <%= toDoList[i] %> </li>
      <% } %>