user
What is the syntax of .ejs files ?
alphonsio

Here are the main EJS tag syntax:

  • <%= ... %>: displays the result of JavaScript in the template (escapes HTML).
  • <%- ... %>: displays the result of JavaScript in the template, without escaping HTML.
  • <% ... %>: for JS logic and control (if, for, while ...).
  • <%- include('path/to/file') %>: includes another EJS template.
  • <%# this is a comment %>: specifyes a comment
  • <%%: displays <% in the template (escapes <%)

EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript. The syntax of EJS is straightforward, using tags to embed JavaScript code within your HTML. Here are the basic tag types used in EJS:

  1. Output Tags:

<%= ... %>: This is used to output the result of JavaScript expressions into the template. It HTML-escapes the content to prevent cross-site scripting (XSS) attacks.

<h1><%= title %></h1>
  1. Unescaped Output Tags:

<%- ... %>: Similar to <%= ... %>, but does not escape the content, allowing you to output HTML directly.

<div><%- htmlContent %></div>
  1. Control Flow Tags:
    <% ... %>: This tag is used for JavaScript logic and control structures like if, for, while, and more. It does not output anything directly.
<% if (user) { %>
   <h2>Hello, <%= user.name %>!</h2>
<% } %>
  1. Include Partial Files:

<%- include('path/to/file') %>: This tag includes another EJS template. The path is relative to the directory the main template is in.

<%- include('partials/header') %>
  1. Comment Tags:

<%# This is a comment %>: This is a comment tag and will not appear in the rendered template.

  1. Escaping Delimiters:

<%%: If you need to include <% in your output, you can escape it like this.

Here's a simple EJS example demonstrating some of these syntax elements:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
</head>
<body>
    <% if (user) { %>
        <h1>Welcome, <%= user.name %>!</h1>
    <% } else { %>
        <h1>Welcome, Guest!</h1>
    <% } %>

    <ul>
    <% for(var i=0; i<items.length; i++) { %>
        <li><%= items[i] %></li>
    <% } %>
    </ul>

    <%- include('partials/footer') %>
</body>
</html>

In this example, you see variables output with <%= %>, JavaScript control flow with <% %>, and an included partial template.