简体   繁体   English

使用循环的节点js和ejs

[英]Node js and ejs using loop

I am new to node.js and now I am facing a problem with EJS template. 我是node.js的新手,现在我面临EJS模板的问题。 I noticed my for loop is not running though the EJS template. 我注意到我的for循环虽然没有通过EJS模板运行。 I tried to make a very basic todo app. 我试图制作一个非常基本的待办事项应用程序。

Here is the hierarchy of the project I made 这是我所做的项目的层次结构

This is my project hierarchy 这是我的项目层次结构

This is my App js module 这是我的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 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 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>

you are missing the condition in looping 您缺少循环条件

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

use i < todoList.length. 使用i <todoList.length。 othertwise it is a infinite loop. 否则,它是一个无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM