EJS
1. install and setup server.js
package needed: express, ejs
server.js:
const express = require('express');
const path = require('path');
const app = express();
app.set('views', path.join(__dirname, 'temp'));
app.set ('view engine', 'ejs');
app.get('/', (req, res)=>{
res.render('index',{
food:[
{name:'banana'},
{name:'apple'}
]
});
})
app.listen(3000, ()=>console.log('listing on 3000'));
so now we’re rendering EJS file “index” now, and the variables inside index.ejs file could be replaced by the food object.
2. EJS for loop, and if statements
Let’s make a “temp” folder and create a **“index.ejs” in it.
in “index.ejs” file, write:
<ul>
<% for(let item of food){ %>
<% if(item.name === 'apple'){ %>
<li>Woo, I am looking for <%=item.name %>!!!!</li>
<% } else { %>
<li>Errr, without apples, I can take <%=item.name %>, it's fine... </li>
<% } %>
<% } %>
</ul>
so:
- every line of EJS code need to be inside the <% %> sign.
- when need to call values, the “=” must be pointing to a specific value.
- indent doesn’t matter, but with indent, it looks better.
3. Layouts
express-ejs-layouts package need to be installed.
additional files under “views” needed:
- Layout.ejs
- other.ejs
Additional code write to server.js
app.get('/other',(req,res)=>{
res.render('other');
})
what’s inside layout.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>This is in the layout file</h1>
<%- body %>
</body>
</html>
This is a very simple layout file, only saying hey I am the layout.
in other.ejs say what every there.
then when every people access the backend, the layout template will always render.