Labs ICT
Pro Login

Client-Side EJS

Using EJS in the browser.

EJS in the Browser

You can run EJS entirely in the browser without a server. Just include the EJS library with a script tag and use ejs.render() to generate HTML from template strings.


<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>

<script>
  var html = ejs.render("<p>Hello, <%= name %>!</p>", {
    name: "Bilal"
  });
  document.getElementById("output").innerHTML = html;
</script>
    

This is perfect for small projects or prototypes where you don't need a full Node.js server.

Rendering Dynamic Content

Client-side EJS lets you generate HTML dynamically based on user input or data fetched from APIs.


<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>

<script>
  var users = [
    { name: "Alice", role: "Admin" },
    { name: "Bob", role: "Editor" },
    { name: "Charlie", role: "Viewer" }
  ];

  var template = "<ul><% users.forEach(function(u) { %>" +
    "<li><%= u.name %> - <%= u.role %></li>" +
    "<% }); %></ul>";

  var html = ejs.render(template, { users: users });
  document.body.innerHTML += html;
</script>
    

You pass data as the second argument to ejs.render() just like you would on the server.

Fetching Templates from Files

You can load template strings from external files or API endpoints, then render them client-side.


<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>

<script>
  fetch("/templates/card.ejs")
    .then(function(response) { return response.text(); })
    .then(function(template) {
      var html = ejs.render(template, {
        title: "My Card",
        body: "This content came from an EJS file."
      });
      document.getElementById("app").innerHTML = html;
    });
</script>
    

This separates your templates from your JavaScript while still keeping everything client-rendered.

Dynamic HTML Generation

Combine EJS with DOM manipulation to build interactive interfaces that update without page reloads.


<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>

<script>
  function renderList(items) {
    var tpl = "<div class='list'><% items.forEach(function(i) { %>" +
      "<div class='item'><%= i %></div>" +
      "<% }); %></div>";
    return ejs.render(tpl, { items: items });
  }

  var result = renderList(["Apple", "Banana", "Cherry"]);
  document.getElementById("output").innerHTML = result;
</script>
    

You create reusable rendering functions and call them whenever your data changes. It's a lightweight approach to dynamic UIs.

Try it Yourself →