EJS

EJS

EJS is a templating engine that can be used with express.js. To use EJS, one has to set the view engine like so:
app.set('view engine', 'ejs'); 
This assumes the ejs files are in a folder called views.
Here is the EJS file:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo List</title>
</head>

<body>
    <h1><%= kindOfDay %></h1> <!-- substitute date into kindOfDay-->
    <ul>
        <% for (let index = 0; index < newListItems.length; index++) { %> <!-- newListItems passed in from app.js-->
        <% const element = newListItems[index]; %>
        <li><%= element %></li>
        <%} %>
    </ul>
    <form action="/" method="post">
        <input id="todoItem" type="text" name="newItem"></input>
        <button type="submit" name="submitButton">Add</button>
    </form>
</body> 
</html>
Here is the app.js file:
const express = require('express');
const bodyParser = require("body-parser");

const app = express();

var items = ["Buy Food", "Cook Food", "Eat Food"];
app.use(bodyParser.urlencoded({ extended: true }));


app.set('view engine', 'ejs');

app.get("/", function (req, res) {
    var day = "";

    var today = new Date();

    var options = {
        weekday: "long",
        day: "numeric",
        month: "long"
    };
    var day = today.toLocaleDateString("en-US", options);
    res.render("list",{kindOfDay: day, newListItems: items});
});

app.post("/", function(req,res){ 
    var item = req.body.newItem;
    items.push(item);
    console.log("TODO item was "+item);
    res.redirect("/");
});

app.listen(3000, function () {
    console.log("Server started on port 3000");
});

References

The Complete 2020 Web Development Bootcamp. Udemy

Comments

Popular posts from this blog

QTreeView and QTableView dynamic changes

C++ strings and string_view