Convert Figma logo to code with AI

tj logoejs

Embedded JavaScript templates for node

4,470
512
4,470
117

Top Related Projects

3,758

HTML Abstraction Markup Language - A Markup Haiku

21,636

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

Minimal templating on steroids.

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

Minimal templating with {{mustaches}} in JavaScript

11,005

Liquid markup language. Safe, customer facing template language for flexible web apps.

Quick Overview

EJS (Embedded JavaScript) is a simple templating language that allows developers to generate HTML markup with plain JavaScript. It provides a straightforward way to embed dynamic content within static HTML pages, making it a popular choice for building web applications and server-side rendered websites.

Pros

  • Simplicity: EJS has a simple and intuitive syntax, making it easy to learn and use, especially for developers familiar with JavaScript.
  • Flexibility: EJS can be used with a variety of server-side frameworks and platforms, including Node.js, Express, and others.
  • Performance: EJS is designed to be fast and efficient, with a small footprint and minimal overhead.
  • Active Development: The EJS project is actively maintained and regularly updated, ensuring compatibility with the latest web technologies.

Cons

  • Limited Functionality: While EJS is a powerful templating engine, it may lack some of the advanced features and functionality found in other templating languages, such as Handlebars or Mustache.
  • Potential Security Risks: If not used properly, EJS can be vulnerable to code injection attacks, so developers must be cautious when handling user input.
  • Lack of Strict Typing: EJS does not enforce strict typing, which can lead to unexpected behavior if developers are not careful with their data types.
  • Dependency on JavaScript: Since EJS is tightly coupled with JavaScript, it may not be the best choice for projects that require a more language-agnostic approach to templating.

Code Examples

Here are a few examples of how to use EJS:

  1. Basic Template Rendering:
const ejs = require('ejs');

const data = { name: 'John Doe', age: 30 };
const html = ejs.render('<h1>Hello, <%= name %>!</h1><p>You are <%= age %> years old.</p>', data);

console.log(html);
  1. Partials and Layouts:
const ejs = require('ejs');

ejs.renderFile('views/layout.ejs', { content: 'This is the main content.' }, (err, html) => {
  if (err) {
    console.error(err);
  } else {
    console.log(html);
  }
});
  1. Conditional Rendering:
const ejs = require('ejs');

const data = { isLoggedIn: true, username: 'johndoe' };
const html = ejs.render('<% if (isLoggedIn) { %><p>Welcome, <%= username %>!</p><% } else { %><p>Please log in.</p><% } %>', data);

console.log(html);
  1. Looping and Iteration:
const ejs = require('ejs');

const data = { items: ['apple', 'banana', 'cherry'] };
const html = ejs.render('<ul><% items.forEach(item => { %><li><%= item %></li><% }); %></ul>', data);

console.log(html);

Getting Started

To get started with EJS, you can follow these steps:

  1. Install the EJS package using npm:
npm install ejs
  1. Create an EJS template file (e.g., template.ejs) with your HTML and EJS tags:
<h1>Hello, <%= name %>!</h1>
<p>You are <%= age %> years old.</p>
  1. In your JavaScript file, import the EJS module and use the ejs.render() function to render the template with your data:
const ejs = require('ejs');

const data = { name: 'John Doe', age: 30 };
const html = ejs.render(fs.readFileSync('template.ejs', 'utf8'), data);

console.log(html);
  1. You can also use EJS with web frameworks like Express.js by setting the view engine and rendering EJS templates:
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res

Competitor Comparisons

3,758

HTML Abstraction Markup Language - A Markup Haiku

Pros of Haml

  • Cleaner, more concise syntax with less closing tags
  • Built-in support for CSS classes and IDs
  • Enforces proper indentation, leading to more readable code

Cons of Haml

  • Steeper learning curve for developers unfamiliar with the syntax
  • Less flexibility in mixing HTML and template code
  • Potentially slower rendering compared to EJS

Code Comparison

Haml:

%ul.menu
  - for item in items
    %li= item.name

EJS:

<ul class="menu">
  <% for (let item of items) { %>
    <li><%= item.name %></li>
  <% } %>
</ul>

Summary

Haml offers a more concise and visually appealing syntax, which can lead to cleaner and more maintainable templates. It's particularly well-suited for projects where a lot of HTML is generated. However, it comes with a steeper learning curve and may be less intuitive for developers accustomed to traditional HTML.

EJS, on the other hand, provides a more familiar syntax for those comfortable with HTML and JavaScript. It offers greater flexibility in mixing HTML and JavaScript code, making it easier to implement complex logic within templates. EJS is generally faster in rendering but may result in more verbose and potentially less readable code compared to Haml.

The choice between Haml and EJS often comes down to personal preference, team familiarity, and specific project requirements.

21,636

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

Pros of Pug

  • Cleaner, more concise syntax with significant whitespace
  • Built-in features like mixins, includes, and inheritance
  • Better performance due to precompilation

Cons of Pug

  • Steeper learning curve for developers new to the syntax
  • Less resemblance to HTML, which can be a barrier for some
  • Potential difficulty when converting existing HTML to Pug

Code Comparison

Pug:

doctype html
html(lang="en")
  head
    title= pageTitle
  body
    h1 Welcome
    p= message

EJS:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title><%= pageTitle %></title>
  </head>
  <body>
    <h1>Welcome</h1>
    <p><%= message %></p>
  </body>
</html>

Summary

Pug offers a more concise syntax and powerful features, making it attractive for developers who prioritize clean code and advanced templating capabilities. However, its unique syntax can be challenging for newcomers and those used to traditional HTML. EJS, on the other hand, provides a more familiar syntax that closely resembles HTML, making it easier to adopt for many developers. The choice between Pug and EJS often depends on project requirements, team preferences, and the learning curve teams are willing to undertake.

Minimal templating on steroids.

Pros of Handlebars.js

  • Logic-less templates with minimal JavaScript in the markup
  • Built-in helpers and custom helper support for more complex logic
  • Precompilation of templates for better runtime performance

Cons of Handlebars.js

  • Steeper learning curve due to its specific syntax and concepts
  • Less flexibility in embedding JavaScript expressions directly in templates
  • Potentially more verbose syntax for simple templating tasks

Code Comparison

EJS:

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

Handlebars:

{{#if user}}
  <h2>{{user.name}}</h2>
{{/if}}

Key Differences

  1. Syntax: EJS uses <% %> for logic and <%= %> for output, while Handlebars uses {{}} for both.
  2. Logic: EJS allows direct JavaScript, whereas Handlebars relies on helpers and built-in constructs.
  3. Learning curve: EJS is more intuitive for developers familiar with JavaScript, while Handlebars requires learning its specific templating language.
  4. Performance: Handlebars offers precompilation, potentially leading to better runtime performance for complex templates.
  5. Flexibility: EJS provides more flexibility with inline JavaScript, while Handlebars enforces a stricter separation of logic and presentation.

Both templating engines have their strengths and are suitable for different use cases. EJS is often preferred for its simplicity and familiarity, while Handlebars is chosen for its clean syntax and logic separation in larger projects.

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
  • Actively maintained with regular updates and improvements

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 %}

Summary

Nunjucks offers more advanced features and better performance for complex templates, making it suitable for larger projects. However, it comes with a steeper learning curve and slightly more verbose syntax. EJS, on the other hand, is simpler and easier to learn, making it a good choice for smaller projects or developers new to templating engines. The choice between the two depends on the project requirements, team expertise, and desired features.

Minimal templating with {{mustaches}} in JavaScript

Pros of Mustache.js

  • Logic-less templates, promoting cleaner separation of concerns
  • Supports multiple languages, making it easier to use across different platforms
  • Smaller file size, leading to faster load times

Cons of Mustache.js

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

Code Comparison

Mustache.js:

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

EJS:

<% var name = "John"; %>
<%= "Hello, " + name + "!" %>

Summary

Mustache.js offers a simpler, logic-less approach to templating with cross-language support, while EJS provides more flexibility and familiar syntax for JavaScript developers. Mustache.js excels in maintaining a clear separation between logic and presentation, but may require more custom JavaScript for complex scenarios. EJS, on the other hand, allows for more straightforward integration of JavaScript within templates, potentially leading to more concise code for certain use cases.

11,005

Liquid markup language. Safe, customer facing template language for flexible web apps.

Pros of Liquid

  • More feature-rich templating language with built-in filters and tags
  • Better suited for e-commerce applications due to Shopify integration
  • Supports more complex logic and control structures

Cons of Liquid

  • Steeper learning curve for developers new to the syntax
  • Less widespread adoption outside of Shopify ecosystem
  • Potentially slower rendering performance for large templates

Code Comparison

EJS:

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

Liquid:

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

Summary

EJS offers a simpler, JavaScript-based templating approach, making it easier for developers familiar with JavaScript. It's lightweight and widely used in various Node.js projects.

Liquid provides a more robust templating language with additional features, making it ideal for e-commerce applications, especially within the Shopify ecosystem. However, it may require more time to master and has less adoption outside of Shopify.

Both templating engines have their strengths, and the choice between them often depends on the specific project requirements and the development team's familiarity with each syntax.

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

EJS

Embedded JavaScript templates.

Build Status


NOTE: Version 2 of EJS makes some breaking changes with this version (notably, removal of the filters feature). Work on v2 is happening here: https://github.com/mde/ejs

File issues for EJS v2 here: https://github.com/mde/ejs/issues


Installation

$ npm install ejs

Features

  • Complies with the Express view system
  • Static caching of intermediate JavaScript
  • Unbuffered code for conditionals etc <% code %>
  • Escapes html by default with <%= code %>
  • Unescaped buffering with <%- code %>
  • Supports tag customization
  • Filter support for designer-friendly templates
  • Includes
  • Client-side support
  • Newline slurping with <% code -%> or <% -%> or <%= code -%> or <%- code -%>

Example

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

Try out a live example now

Usage

ejs.compile(str, options);
// => Function

ejs.render(str, options);
// => str

Options

  • cache Compiled functions are cached, requires filename
  • filename Used by cache to key caches
  • scope Function execution context
  • debug Output generated function body
  • compileDebug When false no debug instrumentation is compiled
  • client Returns standalone compiled function
  • open Open tag, defaulting to "<%"
  • close Closing tag, defaulting to "%>"
    •             All others are template-local variables
      

Includes

Includes are relative to the template with the include statement, for example if you have "./views/users.ejs" and "./views/user/show.ejs" you would use <% include user/show %>. The included file(s) are literally included into the template, no IO is performed after compilation, thus local variables are available to these included templates.

<ul>
  <% users.forEach(function(user){ %>
    <% include user/show %>
  <% }) %>
</ul>

Custom delimiters

Custom delimiters can also be applied globally:

var ejs = require('ejs');
ejs.open = '{{';
ejs.close = '}}';

Which would make the following a valid template:

<h1>{{= title }}</h1>

Filters

EJS conditionally supports the concept of "filters". A "filter chain" is a designer friendly api for manipulating data, without writing JavaScript.

Filters can be applied by supplying the : modifier, so for example if we wish to take the array [{ name: 'tj' }, { name: 'mape' }, { name: 'guillermo' }] and output a list of names we can do this simply with filters:

Template:

<p><%=: users | map:'name' | join %></p>

Output:

<p>Tj, Mape, Guillermo</p>

Render call:

ejs.render(str, {
    users: [
      { name: 'tj' },
      { name: 'mape' },
      { name: 'guillermo' }
    ]
});

Or perhaps capitalize the first user's name for display:

<p><%=: users | first | capitalize %></p>

Filter list

Currently these filters are available:

  • first
  • last
  • capitalize
  • downcase
  • upcase
  • sort
  • sort_by:'prop'
  • size
  • length
  • plus:n
  • minus:n
  • times:n
  • divided_by:n
  • join:'val'
  • truncate:n
  • truncate_words:n
  • replace:pattern,substitution
  • prepend:val
  • append:val
  • map:'prop'
  • reverse
  • get:'prop'

Adding filters

To add a filter simply add a method to the .filters object:

ejs.filters.last = function(obj) {
  return obj[obj.length - 1];
};

Layouts

Currently EJS has no notion of blocks, only compile-time includes, however you may still utilize this feature to implement "layouts" by simply including a header and footer like so:

<% include head %>
<h1>Title</h1>
<p>My page</p>
<% include foot %>

client-side support

include ./ejs.js or ./ejs.min.js and require("ejs").compile(str).

License

(The MIT License)

Copyright (c) 2009-2010 TJ Holowaychuk <tj@vision-media.ca>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NPM DownloadsLast 30 Days