Convert Figma logo to code with AI

mde logoejs

Embedded JavaScript templates -- http://ejs.co

7,699
844
7,699
113

Top Related Projects

4,470

Embedded JavaScript templates for node

Minimal templating with {{mustaches}} in JavaScript

Minimal templating on steroids.

21,636

Pug – robust, elegant, feature rich template engine for Node.js

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

13,347

A declarative, HTML-based language that makes building web apps fun

Quick Overview

EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript. It's a lightweight and flexible solution for creating dynamic web pages, allowing developers to embed JavaScript code directly into HTML templates.

Pros

  • Easy to learn and use, especially for developers familiar with JavaScript
  • Fast performance due to its simple syntax and minimal processing overhead
  • Highly flexible, allowing for both server-side and client-side rendering
  • Supports partials and includes for better code organization and reusability

Cons

  • Limited built-in features compared to more comprehensive templating engines
  • Lack of built-in security features, requiring careful handling of user input
  • Can lead to messy code if not properly structured, especially for complex templates
  • No native support for asynchronous rendering

Code Examples

  1. Basic template rendering:
const ejs = require('ejs');

const template = '<%= name %> is <%= age %> years old';
const data = { name: 'John', age: 30 };

const result = ejs.render(template, data);
console.log(result); // Output: John is 30 years old
  1. Using conditionals in EJS:
<% if (user) { %>
  <h2>Welcome, <%= user.name %>!</h2>
<% } else { %>
  <h2>Please log in</h2>
<% } %>
  1. Iterating over an array:
<ul>
<% items.forEach(function(item) { %>
  <li><%= item.name %></li>
<% }); %>
</ul>
  1. Including a partial:
<%- include('header') %>
<h1>Main Content</h1>
<%- include('footer') %>

Getting Started

To use EJS in your project, first install it via npm:

npm install ejs

Then, in your Node.js application:

const ejs = require('ejs');
const fs = require('fs');

// Read the template file
const template = fs.readFileSync('template.ejs', 'utf-8');

// Render the template with data
const html = ejs.render(template, {
  title: 'My EJS App',
  items: ['Apple', 'Banana', 'Orange']
});

console.log(html);

Create a file named template.ejs with the following content:

<h1><%= title %></h1>
<ul>
<% items.forEach(function(item) { %>
  <li><%= item %></li>
<% }); %>
</ul>

Run your Node.js script to see the rendered HTML output.

Competitor Comparisons

4,470

Embedded JavaScript templates for node

Pros of EJS (tj)

  • Simpler and more lightweight implementation
  • Faster rendering performance for basic templates
  • Easier to integrate into existing projects due to minimal dependencies

Cons of EJS (tj)

  • Less actively maintained (last update in 2015)
  • Fewer features and customization options
  • Limited documentation and community support

Code Comparison

EJS (mde):

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

EJS (tj):

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

The basic syntax for both implementations is identical, making it easy to switch between them. However, EJS (mde) offers more advanced features and helper functions that aren't available in the tj version.

Summary

EJS (tj) is a simpler, more lightweight alternative to EJS (mde). It offers better performance for basic templating needs but lacks the extensive feature set and ongoing development of its counterpart. EJS (mde) provides more robust functionality, better documentation, and active maintenance, making it a better choice for complex projects or those requiring long-term support. The choice between the two depends on the specific requirements of your project and the level of complexity you need in your templating engine.

Minimal templating with {{mustaches}} in JavaScript

Pros of Mustache.js

  • Logic-less templates, promoting cleaner separation of concerns
  • Supports multiple languages, enabling consistent templating across platforms
  • Smaller file size and faster rendering for simple templates

Cons of Mustache.js

  • Limited built-in functionality, requiring custom helpers for complex logic
  • Less flexibility in template syntax compared to EJS
  • Steeper learning curve for developers accustomed to more traditional templating

Code Comparison

Mustache.js:

var view = {
  name: "John",
  greeting: function() {
    return "Hello, " + this.name + "!";
  }
};
var output = Mustache.render("{{greeting}}", view);

EJS:

var view = {
  name: "John",
  greeting: function() {
    return "Hello, " + this.name + "!";
  }
};
var output = ejs.render("<%= greeting() %>", view);

Both Mustache.js and EJS are popular templating engines for JavaScript, each with its own strengths and weaknesses. Mustache.js focuses on logic-less templates, which can lead to cleaner code separation but may require more effort for complex logic. EJS, on the other hand, offers more flexibility and familiarity for developers used to embedded JavaScript syntax. The choice between the two often depends on project requirements and team preferences.

Minimal templating on steroids.

Pros of Handlebars.js

  • Logic-less templates, promoting cleaner separation of concerns
  • Built-in helpers for common operations (e.g., if, each, with)
  • Precompilation support for improved runtime performance

Cons of Handlebars.js

  • Less flexibility in template logic compared to EJS
  • Steeper learning curve for developers new to the syntax
  • Requires additional compilation step for optimal performance

Code Comparison

Handlebars.js:

<ul>
  {{#each items}}
    <li>{{name}}: {{price}}</li>
  {{/each}}
</ul>

EJS:

<ul>
  <% items.forEach(function(item) { %>
    <li><%= item.name %>: <%= item.price %></li>
  <% }); %>
</ul>

Summary

Handlebars.js offers a more structured approach to templating with built-in helpers and logic-less templates, which can lead to cleaner code and better separation of concerns. However, it comes with a steeper learning curve and less flexibility in complex logic scenarios.

EJS, on the other hand, provides more flexibility and familiarity for developers accustomed to JavaScript, allowing for easier integration of complex logic within templates. It lacks some of the built-in features of Handlebars.js but offers a simpler syntax for those who prefer more control over their template logic.

The choice between the two often depends on project requirements, team preferences, and the desired balance between template simplicity and logic flexibility.

21,636

Pug – robust, elegant, feature rich template engine for Node.js

Pros of Pug

  • Concise and clean syntax with significant whitespace, reducing code verbosity
  • Built-in features like mixins and includes for better code organization
  • Powerful language constructs for conditionals and loops

Cons of Pug

  • Steeper learning curve due to its unique syntax
  • Less resemblance to HTML, potentially making it harder for designers to work with
  • Requires compilation step, which can add complexity to the build process

Code Comparison

Pug:

ul
  each item in items
    li= item.name

EJS:

<ul>
  <% items.forEach(function(item) { %>
    <li><%= item.name %></li>
  <% }); %>
</ul>

Summary

Pug offers a more concise syntax and powerful features, but comes with a steeper learning curve and less HTML-like structure. EJS, on the other hand, provides a more familiar syntax for those comfortable with HTML and JavaScript, but can be more verbose. The choice between the two often depends on personal preference and project requirements.

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

Pros of Nunjucks

  • More powerful and feature-rich templating language with inheritance, macros, and asynchronous support
  • Better performance for complex templates and large datasets
  • Extensive documentation and active community support

Cons of Nunjucks

  • Steeper learning curve due to more advanced features
  • Slightly more verbose syntax for basic operations
  • Larger file size and potentially slower initial load times

Code Comparison

EJS:

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

Nunjucks:

{% if user %}
  <h2>{{ user.name }}</h2>
{% endif %}

Both EJS and Nunjucks are popular templating engines for JavaScript, with EJS being simpler and more lightweight, while Nunjucks offers more advanced features and better performance for complex templates. EJS uses a syntax closer to plain JavaScript, making it easier for beginners to pick up, while Nunjucks uses a syntax inspired by Jinja2 and Twig, which may be more familiar to developers coming from Python or PHP backgrounds. The choice between the two often depends on the project's complexity and the team's familiarity with the respective syntaxes.

13,347

A declarative, HTML-based language that makes building web apps fun

Pros of Marko

  • Faster rendering performance due to its streaming and asynchronous nature
  • Built-in components and custom tags for more modular and reusable code
  • Supports both server-side and browser-side rendering out of the box

Cons of Marko

  • Steeper learning curve due to its unique syntax and concepts
  • Smaller community and ecosystem compared to EJS
  • Less suitable for simple templating needs or quick prototyping

Code Comparison

EJS:

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

Marko:

<if(input.user)>
  <h2>${input.user.name}</h2>
</if>

Summary

Marko offers superior performance and more advanced features for complex applications, while EJS provides a simpler, more familiar syntax for basic templating needs. Marko excels in building scalable, component-based applications, whereas EJS is better suited for quick prototyping and simpler server-side rendering tasks. The choice between the two depends on project requirements, team expertise, and performance needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Embedded JavaScript templates
Known Vulnerabilities

Security

Security professionals, before reporting any security issues, please reference the SECURITY.md in this project, in particular, the following: "EJS is effectively a JavaScript runtime. Its entire job is to execute JavaScript. If you run the EJS render method without checking the inputs yourself, you are responsible for the results."

In short, DO NOT submit 'vulnerabilities' that include this snippet of code:

app.get('/', (req, res) => {
  res.render('index', req.query);
});

Installation

$ npm install ejs

Features

  • Control flow with <% %>
  • Escaped output with <%= %> (escape function configurable)
  • Unescaped raw output with <%- %>
  • Newline-trim mode ('newline slurping') with -%> ending tag
  • Whitespace-trim mode (slurp all whitespace) for control flow with <%_ _%>
  • Custom delimiters (e.g. [? ?] instead of <% %>)
  • Includes
  • Client-side support
  • Static caching of intermediate JavaScript
  • Static caching of templates
  • Complies with the Express view system

Example

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

Try EJS online at: https://ionicabizau.github.io/ejs-playground/.

Basic usage

let template = ejs.compile(str, options);
template(data);
// => Rendered HTML string

ejs.render(str, data, options);
// => Rendered HTML string

ejs.renderFile(filename, data, options, function(err, str){
    // str => Rendered HTML string
});

It is also possible to use ejs.render(dataAndOptions); where you pass everything in a single object. In that case, you'll end up with local variables for all the passed options. However, be aware that your code could break if we add an option with the same name as one of your data object's properties. Therefore, we do not recommend using this shortcut.

Important

You should never give end-users unfettered access to the EJS render method, If you do so you are using EJS in an inherently un-secure way.

Options

  • cache Compiled functions are cached, requires filename
  • filename The name of the file being rendered. Not required if you are using renderFile(). Used by cache to key caches, and for includes.
  • root Set template root(s) for includes with an absolute path (e.g, /file.ejs). Can be array to try to resolve include from multiple directories.
  • views An array of paths to use when resolving includes with relative paths.
  • context Function execution context
  • compileDebug When false no debug instrumentation is compiled
  • client When true, compiles a function that can be rendered in the browser without needing to load the EJS Runtime (ejs.min.js).
  • delimiter Character to use for inner delimiter, by default '%'
  • openDelimiter Character to use for opening delimiter, by default '<'
  • closeDelimiter Character to use for closing delimiter, by default '>'
  • debug Outputs generated function body
  • strict When set to true, generated function is in strict mode
  • _with Whether or not to use with() {} constructs. If false then the locals will be stored in the locals object. Set to false in strict mode.
  • destructuredLocals An array of local variables that are always destructured from the locals object, available even in strict mode.
  • localsName Name to use for the object storing local variables when not using with Defaults to locals
  • rmWhitespace Remove all safe-to-remove whitespace, including leading and trailing whitespace. It also enables a safer version of -%> line slurping for all scriptlet tags (it does not strip new lines of tags in the middle of a line).
  • escape The escaping function used with <%= construct. It is used in rendering and is .toString()ed in the generation of client functions. (By default escapes XML).
  • outputFunctionName Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags.
  • async When true, EJS will use an async function for rendering. (Depends on async/await support in the JS runtime).
  • includer Custom function to handle EJS includes, receives (originalPath, parsedPath) parameters, where originalPath is the path in include as-is and parsedPath is the previously resolved path. Should return an object { filename, template }, you may return only one of the properties, where filename is the final parsed path and template is the included content.

This project uses JSDoc. For the full public API documentation, clone the repository and run jake doc. This will run JSDoc with the proper options and output the documentation to out/. If you want the both the public & private API docs, run jake devdoc instead.

Tags

  • <% 'Scriptlet' tag, for control-flow, no output
  • <%_ 'Whitespace Slurping' Scriptlet tag, strips all whitespace before it
  • <%= Outputs the value into the template (escaped)
  • <%- Outputs the unescaped value into the template
  • <%# Comment tag, no execution, no output
  • <%% Outputs a literal '<%'
  • %%> Outputs a literal '%>'
  • %> Plain ending tag
  • -%> Trim-mode ('newline slurp') tag, trims following newline
  • _%> 'Whitespace Slurping' ending tag, removes all whitespace after it

For the full syntax documentation, please see docs/syntax.md.

Includes

Includes either have to be an absolute path, or, if not, are assumed as relative to the template with the include call. For example if you are including ./views/user/show.ejs from ./views/users.ejs you would use <%- include('user/show') %>.

You must specify the filename option for the template with the include call unless you are using renderFile().

You'll likely want to use the raw output tag (<%-) with your include to avoid double-escaping the HTML output.

<ul>
  <% users.forEach(function(user){ %>
    <%- include('user/show', {user: user}) %>
  <% }); %>
</ul>

Includes are inserted at runtime, so you can use variables for the path in the include call (for example <%- include(somePath) %>). Variables in your top-level data object are available to all your includes, but local variables need to be passed down.

NOTE: Include preprocessor directives (<% include user/show %>) are not supported in v3.0+.

Custom delimiters

Custom delimiters can be applied on a per-template basis, or globally:

let ejs = require('ejs'),
    users = ['geddy', 'neil', 'alex'];

// Just one template
ejs.render('<p>[?= users.join(" | "); ?]</p>', {users: users}, {delimiter: '?', openDelimiter: '[', closeDelimiter: ']'});
// => '<p>geddy | neil | alex</p>'

// Or globally
ejs.delimiter = '?';
ejs.openDelimiter = '[';
ejs.closeDelimiter = ']';
ejs.render('<p>[?= users.join(" | "); ?]</p>', {users: users});
// => '<p>geddy | neil | alex</p>'

Caching

EJS ships with a basic in-process cache for caching the intermediate JavaScript functions used to render templates. It's easy to plug in LRU caching using Node's lru-cache library:

let ejs = require('ejs'),
    LRU = require('lru-cache');
ejs.cache = LRU(100); // LRU cache with 100-item limit

If you want to clear the EJS cache, call ejs.clearCache. If you're using the LRU cache and need a different limit, simple reset ejs.cache to a new instance of the LRU.

Custom file loader

The default file loader is fs.readFileSync, if you want to customize it, you can set ejs.fileLoader.

let ejs = require('ejs');
let myFileLoad = function (filePath) {
  return 'myFileLoad: ' + fs.readFileSync(filePath);
};

ejs.fileLoader = myFileLoad;

With this feature, you can preprocess the template before reading it.

Layouts

EJS does not specifically support blocks, but layouts can be implemented by including headers and footers, like so:

<%- include('header') -%>
<h1>
  Title
</h1>
<p>
  My page
</p>
<%- include('footer') -%>

Client-side support

Go to the Latest Release, download ./ejs.js or ./ejs.min.js. Alternately, you can compile it yourself by cloning the repository and running jake build (or $(npm bin)/jake build if jake is not installed globally).

Include one of these files on your page, and ejs should be available globally.

Example

<div id="output"></div>
<script src="ejs.min.js"></script>
<script>
  let people = ['geddy', 'neil', 'alex'],
      html = ejs.render('<%= people.join(", "); %>', {people: people});
  // With jQuery:
  $('#output').html(html);
  // Vanilla JS:
  document.getElementById('output').innerHTML = html;
</script>

Caveats

Most of EJS will work as expected; however, there are a few things to note:

  1. Obviously, since you do not have access to the filesystem, ejs.renderFile() won't work.
  2. For the same reason, includes do not work unless you use an include callback. Here is an example:
let str = "Hello <%= include('file', {person: 'John'}); %>",
    fn = ejs.compile(str, {client: true});

fn(data, null, function(path, d){ // include callback
  // path -> 'file'
  // d -> {person: 'John'}
  // Put your code here
  // Return the contents of file as a string
}); // returns rendered string

See the examples folder for more details.

CLI

EJS ships with a full-featured CLI. Options are similar to those used in JavaScript code:

  • -o / --output-file FILE Write the rendered output to FILE rather than stdout.
  • -f / --data-file FILE Must be JSON-formatted. Use parsed input from FILE as data for rendering.
  • -i / --data-input STRING Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering.
  • -m / --delimiter CHARACTER Use CHARACTER with angle brackets for open/close (defaults to %).
  • -p / --open-delimiter CHARACTER Use CHARACTER instead of left angle bracket to open.
  • -c / --close-delimiter CHARACTER Use CHARACTER instead of right angle bracket to close.
  • -s / --strict When set to true, generated function is in strict mode
  • -n / --no-with Use 'locals' object for vars rather than using with (implies --strict).
  • -l / --locals-name Name to use for the object storing local variables when not using with.
  • -w / --rm-whitespace Remove all safe-to-remove whitespace, including leading and trailing whitespace.
  • -d / --debug Outputs generated function body
  • -h / --help Display this help message.
  • -V/v / --version Display the EJS version.

Here are some examples of usage:

$ ejs -p [ -c ] ./template_file.ejs -o ./output.html
$ ejs ./test/fixtures/user.ejs name=Lerxst
$ ejs -n -l _ ./some_template.ejs -f ./data_file.json

Data input

There is a variety of ways to pass the CLI data for rendering.

Stdin:

$ ./test/fixtures/user_data.json | ejs ./test/fixtures/user.ejs
$ ejs ./test/fixtures/user.ejs < test/fixtures/user_data.json

A data file:

$ ejs ./test/fixtures/user.ejs -f ./user_data.json

A command-line option (must be URI-encoded):

./bin/cli.js -i %7B%22name%22%3A%20%22foo%22%7D ./test/fixtures/user.ejs

Or, passing values directly at the end of the invocation:

./bin/cli.js -m $ ./test/fixtures/user.ejs name=foo

Output

The CLI by default send output to stdout, but you can use the -o or --output-file flag to specify a target file to send the output to.

IDE Integration with Syntax Highlighting

VSCode:Javascript EJS by DigitalBrainstem

Related projects

There are a number of implementations of EJS:

License

Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)


EJS Embedded JavaScript templates copyright 2112 mde@fleegix.org.

NPM DownloadsLast 30 Days