1 Embedded JavaScript templates<br/>
2 [![Build Status](https://img.shields.io/travis/mde/ejs/master.svg?style=flat)](https://travis-ci.org/mde/ejs)
3 [![Developing Dependencies](https://img.shields.io/david/dev/mde/ejs.svg?style=flat)](https://david-dm.org/mde/ejs?type=dev)
4 [![Known Vulnerabilities](https://snyk.io/test/npm/ejs/badge.svg?style=flat)](https://snyk.io/test/npm/ejs)
5 =============================
15 * Control flow with `<% %>`
16 * Escaped output with `<%= %>` (escape function configurable)
17 * Unescaped raw output with `<%- %>`
18 * Newline-trim mode ('newline slurping') with `-%>` ending tag
19 * Whitespace-trim mode (slurp all whitespace) for control flow with `<%_ _%>`
20 * Custom delimiters (e.g. `[? ?]` instead of `<% %>`)
23 * Static caching of intermediate JavaScript
24 * Static caching of templates
25 * Complies with the [Express](http://expressjs.com) view system
31 <h2><%= user.name %></h2>
35 Try EJS online at: https://ionicabizau.github.io/ejs-playground/.
40 let template = ejs.compile(str, options);
42 // => Rendered HTML string
44 ejs.render(str, data, options);
45 // => Rendered HTML string
47 ejs.renderFile(filename, data, options, function(err, str){
48 // str => Rendered HTML string
52 It is also possible to use `ejs.render(dataAndOptions);` where you pass
53 everything in a single object. In that case, you'll end up with local variables
54 for all the passed options. However, be aware that your code could break if we
55 add an option with the same name as one of your data object's properties.
56 Therefore, we do not recommend using this shortcut.
60 - `cache` Compiled functions are cached, requires `filename`
61 - `filename` The name of the file being rendered. Not required if you
62 are using `renderFile()`. Used by `cache` to key caches, and for includes.
63 - `root` Set project root for includes with an absolute path (e.g, /file.ejs).
64 Can be array to try to resolve include from multiple directories.
65 - `views` An array of paths to use when resolving includes with relative paths.
66 - `context` Function execution context
67 - `compileDebug` When `false` no debug instrumentation is compiled
68 - `client` When `true`, compiles a function that can be rendered
69 in the browser without needing to load the EJS Runtime
70 ([ejs.min.js](https://github.com/mde/ejs/releases/latest)).
71 - `delimiter` Character to use for inner delimiter, by default '%'
72 - `openDelimiter` Character to use for opening delimiter, by default '<'
73 - `closeDelimiter` Character to use for closing delimiter, by default '>'
74 - `debug` Outputs generated function body
75 - `strict` When set to `true`, generated function is in strict mode
76 - `_with` Whether or not to use `with() {}` constructs. If `false`
77 then the locals will be stored in the `locals` object. Set to `false` in strict mode.
78 - `destructuredLocals` An array of local variables that are always destructured from
79 the locals object, available even in strict mode.
80 - `localsName` Name to use for the object storing local variables when not using
81 `with` Defaults to `locals`
82 - `rmWhitespace` Remove all safe-to-remove whitespace, including leading
83 and trailing whitespace. It also enables a safer version of `-%>` line
84 slurping for all scriptlet tags (it does not strip new lines of tags in
85 the middle of a line).
86 - `escape` The escaping function used with `<%=` construct. It is
87 used in rendering and is `.toString()`ed in the generation of client functions.
88 (By default escapes XML).
89 - `outputFunctionName` Set to a string (e.g., 'echo' or 'print') for a function to print
90 output inside scriptlet tags.
91 - `async` When `true`, EJS will use an async function for rendering. (Depends
92 on async/await support in the JS runtime.
93 - `includer` Custom function to handle EJS includes, receives `(originalPath, parsedPath)`
94 parameters, where `originalPath` is the path in include as-is and `parsedPath` is the
95 previously resolved path. Should return an object `{ filename, template }`,
96 you may return only one of the properties, where `filename` is the final parsed path and `template`
97 is the included content.
99 This project uses [JSDoc](http://usejsdoc.org/). For the full public API
100 documentation, clone the repository and run `jake doc`. This will run JSDoc
101 with the proper options and output the documentation to `out/`. If you want
102 the both the public & private API docs, run `jake devdoc` instead.
106 - `<%` 'Scriptlet' tag, for control-flow, no output
107 - `<%_` 'Whitespace Slurping' Scriptlet tag, strips all whitespace before it
108 - `<%=` Outputs the value into the template (escaped)
109 - `<%-` Outputs the unescaped value into the template
110 - `<%#` Comment tag, no execution, no output
111 - `<%%` Outputs a literal '<%'
112 - `%%>` Outputs a literal '%>'
113 - `%>` Plain ending tag
114 - `-%>` Trim-mode ('newline slurp') tag, trims following newline
115 - `_%>` 'Whitespace Slurping' ending tag, removes all whitespace after it
117 For the full syntax documentation, please see [docs/syntax.md](https://github.com/mde/ejs/blob/master/docs/syntax.md).
121 Includes either have to be an absolute path, or, if not, are assumed as
122 relative to the template with the `include` call. For example if you are
123 including `./views/user/show.ejs` from `./views/users.ejs` you would
124 use `<%- include('user/show') %>`.
126 You must specify the `filename` option for the template with the `include`
127 call unless you are using `renderFile()`.
129 You'll likely want to use the raw output tag (`<%-`) with your include to avoid
130 double-escaping the HTML output.
134 <% users.forEach(function(user){ %>
135 <%- include('user/show', {user: user}) %>
140 Includes are inserted at runtime, so you can use variables for the path in the
141 `include` call (for example `<%- include(somePath) %>`). Variables in your
142 top-level data object are available to all your includes, but local variables
143 need to be passed down.
145 NOTE: Include preprocessor directives (`<% include user/show %>`) are
146 not supported in v3.0+.
150 Custom delimiters can be applied on a per-template basis, or globally:
153 let ejs = require('ejs'),
154 users = ['geddy', 'neil', 'alex'];
157 ejs.render('<p>[?= users.join(" | "); ?]</p>', {users: users}, {delimiter: '?', openDelimiter: '[', closeDelimiter: ']'});
158 // => '<p>geddy | neil | alex</p>'
162 ejs.openDelimiter = '[';
163 ejs.closeDelimiter = ']';
164 ejs.render('<p>[?= users.join(" | "); ?]</p>', {users: users});
165 // => '<p>geddy | neil | alex</p>'
170 EJS ships with a basic in-process cache for caching the intermediate JavaScript
171 functions used to render templates. It's easy to plug in LRU caching using
172 Node's `lru-cache` library:
175 let ejs = require('ejs'),
176 LRU = require('lru-cache');
177 ejs.cache = LRU(100); // LRU cache with 100-item limit
180 If you want to clear the EJS cache, call `ejs.clearCache`. If you're using the
181 LRU cache and need a different limit, simple reset `ejs.cache` to a new instance
184 ### Custom file loader
186 The default file loader is `fs.readFileSync`, if you want to customize it, you can set ejs.fileLoader.
189 let ejs = require('ejs');
190 let myFileLoad = function (filePath) {
191 return 'myFileLoad: ' + fs.readFileSync(filePath);
194 ejs.fileLoader = myFileLoad;
197 With this feature, you can preprocess the template before reading it.
201 EJS does not specifically support blocks, but layouts can be implemented by
202 including headers and footers, like so:
206 <%- include('header') -%>
213 <%- include('footer') -%>
216 ## Client-side support
218 Go to the [Latest Release](https://github.com/mde/ejs/releases/latest), download
219 `./ejs.js` or `./ejs.min.js`. Alternately, you can compile it yourself by cloning
220 the repository and running `jake build` (or `$(npm bin)/jake build` if jake is
221 not installed globally).
223 Include one of these files on your page, and `ejs` should be available globally.
228 <div id="output"></div>
229 <script src="ejs.min.js"></script>
231 let people = ['geddy', 'neil', 'alex'],
232 html = ejs.render('<%= people.join(", "); %>', {people: people});
234 $('#output').html(html);
236 document.getElementById('output').innerHTML = html;
242 Most of EJS will work as expected; however, there are a few things to note:
244 1. Obviously, since you do not have access to the filesystem, `ejs.renderFile()` won't work.
245 2. For the same reason, `include`s do not work unless you use an `include callback`. Here is an example:
247 let str = "Hello <%= include('file', {person: 'John'}); %>",
248 fn = ejs.compile(str, {client: true});
250 fn(data, null, function(path, d){ // include callback
252 // d -> {person: 'John'}
253 // Put your code here
254 // Return the contents of file as a string
255 }); // returns rendered string
258 See the [examples folder](https://github.com/mde/ejs/tree/master/examples) for more details.
262 EJS ships with a full-featured CLI. Options are similar to those used in JavaScript code:
264 - `-o / --output-file FILE` Write the rendered output to FILE rather than stdout.
265 - `-f / --data-file FILE` Must be JSON-formatted. Use parsed input from FILE as data for rendering.
266 - `-i / --data-input STRING` Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering.
267 - `-m / --delimiter CHARACTER` Use CHARACTER with angle brackets for open/close (defaults to %).
268 - `-p / --open-delimiter CHARACTER` Use CHARACTER instead of left angle bracket to open.
269 - `-c / --close-delimiter CHARACTER` Use CHARACTER instead of right angle bracket to close.
270 - `-s / --strict` When set to `true`, generated function is in strict mode
271 - `-n / --no-with` Use 'locals' object for vars rather than using `with` (implies --strict).
272 - `-l / --locals-name` Name to use for the object storing local variables when not using `with`.
273 - `-w / --rm-whitespace` Remove all safe-to-remove whitespace, including leading and trailing whitespace.
274 - `-d / --debug` Outputs generated function body
275 - `-h / --help` Display this help message.
276 - `-V/v / --version` Display the EJS version.
278 Here are some examples of usage:
281 $ ejs -p [ -c ] ./template_file.ejs -o ./output.html
282 $ ejs ./test/fixtures/user.ejs name=Lerxst
283 $ ejs -n -l _ ./some_template.ejs -f ./data_file.json
288 There is a variety of ways to pass the CLI data for rendering.
293 $ ./test/fixtures/user_data.json | ejs ./test/fixtures/user.ejs
294 $ ejs ./test/fixtures/user.ejs < test/fixtures/user_data.json
300 $ ejs ./test/fixtures/user.ejs -f ./user_data.json
303 A command-line option (must be URI-encoded):
306 ./bin/cli.js -i %7B%22name%22%3A%20%22foo%22%7D ./test/fixtures/user.ejs
309 Or, passing values directly at the end of the invocation:
312 ./bin/cli.js -m $ ./test/fixtures/user.ejs name=foo
317 The CLI by default send output to stdout, but you can use the `-o` or `--output-file`
318 flag to specify a target file to send the output to.
320 ## IDE Integration with Syntax Highlighting
322 VSCode:Javascript EJS by *DigitalBrainstem*
326 There are a number of implementations of EJS:
328 * TJ's implementation, the v1 of this library: https://github.com/tj/ejs
329 * EJS Embedded JavaScript Framework on Google Code: https://code.google.com/p/embeddedjavascript/
330 * Sam Stephenson's Ruby implementation: https://rubygems.org/gems/ejs
331 * Erubis, an ERB implementation which also runs JavaScript: http://www.kuwata-lab.com/erubis/users-guide.04.html#lang-javascript
332 * DigitalBrainstem EJS Language support: https://github.com/Digitalbrainstem/ejs-grammar
336 Licensed under the Apache License, Version 2.0
337 (<http://www.apache.org/licenses/LICENSE-2.0>)
340 EJS Embedded JavaScript templates copyright 2112