Labs ICT
Pro Login

Scriptlet Tags

Running any JavaScript in your templates.

What Are Scriptlet Tags?

Scriptlet tags let you run any JavaScript inside your EJS templates. They use the <% and %> delimiters. Anything between them gets executed as regular JavaScript — no output, just logic.


<%
  var name = "Bilal";
  var age = 25;
%>
    

This sets two variables. They won't print anything by themselves, but you can use them later with output tags.

Variable Declarations

You can declare variables, arrays, and objects right inside scriptlet tags. These are perfect for setting up data before rendering.


<%
  var items = ["HTML", "CSS", "JavaScript", "EJS"];
  var total = items.length;
%>
<p>We have <%= total %> items to learn.</p>
    

Variables declared with var in scriptlets are scoped to the template. They won't leak into other files.

Calculations and Logic

Scriptlets are great for doing math or making decisions before outputting anything.


<%
  var price = 49.99;
  var tax = price * 0.08;
  var total = price + tax;
%>
<p>Subtotal: $<%= price.toFixed(2) %></p>
<p>Tax: $<%= tax.toFixed(2) %></p>
<p>Total: $<%= total.toFixed(2) %></p>
    

All the math happens server-side. The browser just sees clean HTML with the final values filled in.

Multi-Line Code Blocks

You can write as much JavaScript as you need inside a single scriptlet tag. Break it across multiple lines — it all runs as one block.


<%
  function greet(hour) {
    if (hour < 12) return "Good morning";
    if (hour < 18) return "Good afternoon";
    return "Good evening";
  }

  var now = new Date().getHours();
  var greeting = greet(now);
%>
<h2><%= greeting %>, visitor!</h2>
    

You can define functions, loop through arrays, and handle complex logic — all in one scriptlet block.

Function Calls and Expressions

Scriptlets can call functions, run methods, and evaluate any valid JavaScript expression. This makes them incredibly flexible.


<%
  var colors = ["red", "green", "blue"].map(function(c) {
    return c.toUpperCase();
  });
%>
<ul>
  <% colors.forEach(function(color) { %>
    <li><%= color %></li>
  <% }); %>
</ul>
    

The scriptlet runs the map method, then loops through the result with another scriptlet. This pattern is common in real-world templates.

Try it Yourself →