BootCamp by Dr.Angela
1. What is EJS?
- EJS (Embedded JavaScript) is a templating engine for Node.js
- Key Concepts
- Templating : Allows you to generate dynamic HTML using JavaScript
- Separation of Concerns : Frontend(HTML, CSS), Backend(JavaScript)
- Other Templating Languages : Python(Jinja), PHP(Twig), JavaScript(EJS)
- How EJS Works : ex)
<% for (let i = 0; i < items.length; i++) { %>
<li><%= items[i] %></li>
<% } %>- JavaScript runs inside HTML, <%= %> outputs data to the page
- Rendering with Express
- Static : ex)
res.sendFile("index.html"); - Dynamic (EJS) : ex)
app.post("/submit", (req, res) => { res.render("index.ejs", { name: req.body["name"] }); });<body> <h1>Hello <%= name %></h1> </body>
- Static : ex)
2. EJS Tags
- <%= variable %> : output value
- <% code %> : execute JavaScript
- <%- html %> : render HTML (unescaped)
- <%% %%> : display <% %> literally
- <%# comment %> : comment (not executed)
- <%- include("header.ejs") %> : Include (Partials), Used to reuse components (header, footer, etc.)
- Using JavaScript in EJS
3. Passing Data
- Server → EJS : Pass data using
res.render()- If no data exists : Use default values or locals
- EJS → Server : Use forms with method="POST"
4. Partials & Layouts
- Static files :
app.use(express.static("public")); - Templating syntax : <% %>(logic), <%= %>(output), <%- %>(raw HTML)
- Partials : ex) <%- include("header.ejs") %>, <%- include("footer.ejs") %>
Helps avoid code duplication, Improves maintainability
Javascript Tip
Variable Keywords : const(cannot be reassigned), let(can be reassigned)
For Each : ex)
array.forEach((element, index, array) => {
console.log(element);
console.log(index);
});
Top comments (0)