Labs ICT
⭐ Pro Login

Filters

Transforming output with helper functions.

2 min read | EJS Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

What Are Filters?

Filters let you transform data right inside your output tags. Instead of modifying values in a scriptlet first, you can apply a function inline with the pipe character.


<p><?= name | upper ?></p>
    

Filters are a shorthand for calling a function on a value. They keep your templates clean and readable.

Uppercasing Text

A common use for filters is formatting strings. You can create an uppercasing filter and apply it anywhere.


<%
  var filters = {
    upper: function(str) {
      return str.toUpperCase();
    }
  };
%>
<p><?= title | upper ?></p>
    

Define your filters as a helper object, then reference them with the pipe. It's like a built-in formatting tool.

Formatting Dates

Filters are perfect for date formatting. Instead of writing long date logic in your template, wrap it in a filter function.


<%
  var filters = {
    formatDate: function(date) {
      var d = new Date(date);
      return d.toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric"
      });
    }
  };
%>
<p>Published: <?= publishDate | formatDate ?></p>
    

Your template stays focused on structure while the filter handles the formatting logic.

Piping Multiple Transforms

You can chain multiple filters together to apply several transformations in sequence.


<%
  var filters = {
    upper: function(str) { return str.toUpperCase(); },
    truncate: function(str) {
      return str.length > 20 ? str.substring(0, 20) + "..." : str;
    },
    escapeHtml: function(str) {
      return str.replace(/&/g, "&amp;").replace(/</g, "&lt;");
    }
  };
%>
<p><?= longText | truncate | upper ?></p>
    

Each filter processes the output of the previous one. This keeps complex transformations organized and reusable.