EJS - Daily Journal Project


Posted by pei_______ on 2022-06-10

學習重點

  1. If you clone something from GitHub, you might get a list in pakage.json like this:

    {
    "name": "ejs-challenge",
    "version": "1.0.0",
    "description": "",
    "main": "app.js",
    "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
     "body-parser": "^1.18.3",
     "ejs": "^3.1.8",
     "express": "^4.16.3",
     "lodash": "^4.17.21"
    }
    }
    

    Then you can just key $ npm intall for install all the npm packages on the list

  2. Array.forEach() replace for loop

    <% posts.forEach(function(post) { %>
    <div>
     <h1><%= post.title %></h1>
     <p><%= post.content %></p>
    </div>
    <% }) %>
    
  3. Express Routing Parameters

    app.get('/users/:userId', (req, res) => {
    console.log(req.params);
    })
    

    So if you get in "localhost:3000/users/penny", you'll get "penny" on terminal.

  4. lodash - lowerCase()

     $ npm install lodash
    
     const _ = require("lodash");
     const lowerCaseText = _.lowerCase(text);
    
  5. String.substring()

     <p><%= post.content.substring(0,100) + "..." %>
    
  6. 在href中放入EJS語法

     <a href="post/<%=post.title %>">Read More</a>
    

Daily Journal Project

app.js

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const lodash = require('lodash');

const homeStartingContent = "Lacus vel facilisis volutpat est velit egestas dui id ornare. Semper auctor neque vitae tempus quam. Sit amet cursus sit amet dictum sit amet justo. Viverra tellus in hac habitasse. Imperdiet proin fermentum leo vel orci porta. Donec ultrices tincidunt arcu non sodales neque sodales ut. Mattis molestie a iaculis at erat pellentesque adipiscing. Magnis dis parturient montes nascetur ridiculus mus mauris vitae ultricies. Adipiscing elit ut aliquam purus sit amet luctus venenatis lectus. Ultrices vitae auctor eu augue ut lectus arcu bibendum at. Odio euismod lacinia at quis risus sed vulputate odio ut. Cursus mattis molestie a iaculis at erat pellentesque adipiscing.";
const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";

const app = express();

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

let posts = [];

app.get("/", function(req, res) {
  res.render("home", {
    homeStartingContent: homeStartingContent,
    posts: posts
  })
})

app.get("/post/:postTitle", function(req, res) {

  const postTitle = lodash.lowerCase(req.params.postTitle);

  posts.forEach(function(post) {

    const lowerTitle = lodash.lowerCase(post.title);

    if (postTitle == lowerTitle) {
      console.log(post);
      res.render("post", {
        post: post
      });
    }
  })

})


app.get("/about", function(req, res) {
  res.render("about", {
    aboutContent: aboutContent
  })
})

app.get("/contact", function(req, res) {
  res.render("contact", {
    contactContent: contactContent
  })
})

app.get("/compose", function(req, res) {
  res.render("compose");
})

app.post("/compose", function(req, res) {
  const newPost = {
    title: req.body.postTitle,
    content: req.body.postBody
  }

  posts.push(newPost);
  res.redirect("/");
})




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

home.ejs

<%- include("partials/header"); -%>

<h1>Hello</h1>
<p><%= homeStartingContent %></p>

<% posts.forEach(function(post) { %>
<div>
  <h1><%= post.title %></h1>
  <p><%= post.content.substring(0,100) + "..." %>
    <a href="post/<%=post.title %>">Read More</a>
  </p>
</div>
<% }) %>

<%- include("partials/footer"); -%>

post.ejs

<%- include("partials/header"); -%>

<h1><%= post.title %></h1>
<p><%= post.content %></p>

<%- include("partials/footer"); -%>

部分略,完整語法見GitHub


#EJS #node.js #web系列







Related Posts

[ week 2 ]  來打造 JaveScript 的基礎 - 變數 與 型別

[ week 2 ] 來打造 JaveScript 的基礎 - 變數 與 型別

重載父類別元素 (當類別裡含有自己的類別List的時候)

重載父類別元素 (當類別裡含有自己的類別List的時候)

C# List相關應用

C# List相關應用


Comments