mde / ejs

Embedded JavaScript templates -- http://ejs.co
Apache License 2.0
7.66k stars 834 forks source link

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

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

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

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="https://github.com/mde/ejs/raw/main/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:

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.