EJS(Embedded JavaScript templates)

GET STARTED

1.

1
npm install ejs

2.

https://github.com/mde/ejs/wiki/Using-EJS-with-Express

In Express v4, a very basic setup using EJS would look like the following. (This assumes a views directory containing an index.ejs page.)

1
2
3
4
5
6
7
8
9
10
let express = require('express');
let app = express();

app.set('view engine', 'ejs'); // TELL APP TO USE EJS

app.get('/', (req, res) => {
res.render('index', {foo: 'FOO'}); // rendering a page called index
});

app.listen(4000, () => console.log('Example app listening on port 4000!'));
  1. create views/list.ejs directory

    list.ejs is used to hold html content

    like:

    list.ejs:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>To do list</title>
    </head>
    <body>
    <h1><%= kindOfDay %> List</h1>
    </body>
    </html>

    app.js:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    const express = require("express");
    const app = express();
    const bodyParser = require("body-parser");

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

    app.get("/", function (req, res) {
    var today = new Date();
    var currentDay = today.getDay();
    var day = "";

    switch (currentDay) {
    case 0:
    day = "Sunday";
    break;
    case 1:
    day = "Monday";
    break;
    case 2:
    day = "Tuesday";
    break;
    case 3:
    day = "Wednesday";
    break;
    case 4:
    day = "Thursday";
    break;
    case 5:
    day = "Friday";
    break;
    case 6:
    day = "Thursday";
    break;
    default:
    console.log("Invalid day");
    }

    res.render("list", { kindOfDay: day }); // it will go and find wiews folder and the list.ejs file inside of it, replace kindOfDay with day
    });

    app.listen(3000, function () {
    console.log("listening on 3000");
    });

  2. add js logic in ejs template

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>To do list</title>
    </head>
    <body>
    <!-- add <% %> if it's javascript -->
    <% if(kindOfDay==="Saturday" || kindOfDay==="Sunday"){ %>
    <h1 style="color: purple"><%= kindOfDay %> ToDo List</h1>
    <% }else{ %>
    <h1 style="color: blue"><%= kindOfDay %> ToDo List</h1>
    <% } %>
    </body>
    </html>

    add list (Project_todolistV1)

  • ejs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>To do list</title>
</head>
<body>
<h1><%= kindOfDay %></h1>
<ul>
<% for( var i = 0; i <newListItems.length; i++) { %>
<li><%= newListItems[i] %></li>
<% } %>
</ul>
<form action="/" method="post" class="">
<input type="text" name="newItem" placeholder="todo..." />
<button type="submit" name="" button>add</button>
</form>
</body>
</html>

  • app.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    const express = require("express");
    const app = express();
    const bodyParser = require("body-parser");
    app.use(bodyParser.urlencoded({ extended: true }));
    app.set("view engine", "ejs");

    var items = ["buy food"];

    app.get("/", function (req, res) {
    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) {
    items.push(req.body.newItem); // add new item to the array
    res.redirect("/"); //redirect to homeroute -> app.get("/")
    // res.render("list", { newListItem: item }); cant put it here, needed to be put in app.get
    });

    app.listen(3000, function () {
    console.log("listening on 3000");
    });

    Scope:

    看笔记

for EJS, go to find the Project_todolistV1, i have all the notes in the coding

Project_Blog

npm install

npm install will go through our package.json and install the dependencies that we’ve already specified.

this is also the first step you need to do when you pull the coding of a project from github.

1. render home.ejs

  • for ejs template, the page we want to render has to be something.ejs and it has to be inside a folder called views, in the root of our main project folder.

2. pass the data from app.js to home.ejs template

after this step, we’ll have css style applied to this web page.

1
2
3
4
5
6
If you would like to retain vscodes html formatter for html files, but leverage prettier for other files you can set the following in settings.json. ctrl+shift+p

"editor.formatOnSave": true,
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
}

and need to modify <%- include(“partials/header”) -%>

5. create other pages and pass data into the corresponding pages

7. render post page

8. get input data of post page in console

9. create a javascript object that’s simply called post and it store both the title and the postContent

10. add that post object into an array

11. log the postContent into home.ejs

Array.prototype.forEach()

loop through the array

1
2
3
4
5
array.forEach(function(letter){

console.log(letter);

});

route parameter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

const express = require('express');
const e = require('express');
const app = express();
const PORT = 3000;

const student = express.Router();
app.use('/student', student);

student.get('/profile/:start/:end', function (req, res) {
console.log("Starting Page: ", req.params.start);
console.log("Ending Page: ", req.params.end);
res.send();
})

app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
  • using colon and then we’re going to give our parameter a name.

if there’s a colon then it’s a parameter. if no colon then it’s just a string

Output: Now open your browser and make a GET request to http://localhost:3000/student/profile/12/17, now you can see the following output on your console:

1
2
3
Server listening on PORT 3000
Starting Page: 12
Ending Page: 17

Lodash lib

12. deal with url

1
2
3
4
5
6
7
8
9
app.get("/post/:title", function (req, res) {
const urlTitle = _.lowerCase(req.params.title);
postList.forEach(function (post) {
const postTitle = _.lowerCase(post.title);
if (postTitle === urlTitle) {
console.log("match!");
}
});
});

13. when you type /title1 in url tab you can open title1 page on web

1
2
3
4
5
6
7
8
9
10
11
12
13
app.get("/post/:title", function (req, res) {
const urlTitle = _.lowerCase(req.params.title);
postList.forEach(function (post) {
const postTitle = _.lowerCase(post.title);
if (postTitle === urlTitle) {
console.log("match!");
res.render("post", {
title: post.title,
content: post.content,
});
}
});
});