EJS

Directory Structure

Test02_EXPRESS/
β”œβ”€β”€ data
β”‚   └── user.json
β”œβ”€β”€ node_modules
β”œβ”€β”€ package.json
β”œβ”€β”€ public
β”‚   └── css
β”‚       └── style.css
β”œβ”€β”€ router
β”‚   └── main.js
β”œβ”€β”€ server.js
└── views
    β”œβ”€β”€ body.ejs
    β”œβ”€β”€ header.ejs
    └── index.ejs

1. Add dependency

1-1 Update package.json

package.json

  • body-parser

    : Handles POST data

  • express-session

    : Session management

Install the modules

1-2 Update `server.js``

server.js

  • fs

    • A Node.js built-in module imported to open files

  • secret

    • A sign value for arbitrarily modifying cookies!

    • You can put any value you want

  • resave

    • A value that determines whether to always save the session

    • The express-session documentation recommends setting this value to false and setting it to true as needed!

  • saveUninitialized

    • An uninitialized session refers to a session that is newly created but not modified

    • The documentation recommends setting it to true!

2. EJS Template Engine

  • A module that reads a template and converts the file to HTML format according to the engine's syntax and settings

  • You can use <% %> in HTML to use server data or execute code!

Syntax

2-1. Passing data to the VIEW

main.js

  • By passing JSON data as the second argument of the render method, the data becomes available on the page

2-2. Accessing data & looping in the VIEW

views > index.ejs

execute

result

image-20200406024630806

2-3. Splitting EJS

Just like in PHP or Rails, in EJS you can also split code into multiple files and import them!

Importing a File

views > header.ejs

views > body.ejs

Modify views > index.ejs!

This is fun!!!

Last updated