433942984f1e3d5233813e0e666d1f7b0a3268bcc65856bb95fea02bcf9d74ab9cd6481dfaea7a1fb83dbb5f90506a7370578e804b50326b7dda311e3a5e48 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # EJS
  2. Embedded JavaScript templates
  3. [![Build Status](https://img.shields.io/travis/mde/ejs/master.svg?style=flat)](https://travis-ci.org/mde/ejs)
  4. [![Developing Dependencies](https://img.shields.io/david/dev/mde/ejs.svg?style=flat)](https://david-dm.org/mde/ejs?type=dev)
  5. [![Known Vulnerabilities](https://snyk.io/test/npm/ejs/badge.svg?style=flat)](https://snyk.io/test/npm/ejs)
  6. ## Installation
  7. ```bash
  8. $ npm install ejs
  9. ```
  10. ## Features
  11. * Control flow with `<% %>`
  12. * Escaped output with `<%= %>` (escape function configurable)
  13. * Unescaped raw output with `<%- %>`
  14. * Newline-trim mode ('newline slurping') with `-%>` ending tag
  15. * Whitespace-trim mode (slurp all whitespace) for control flow with `<%_ _%>`
  16. * Custom delimiters (e.g., use `<? ?>` instead of `<% %>`)
  17. * Includes
  18. * Client-side support
  19. * Static caching of intermediate JavaScript
  20. * Static caching of templates
  21. * Complies with the [Express](http://expressjs.com) view system
  22. ## Example
  23. ```ejs
  24. <% if (user) { %>
  25. <h2><%= user.name %></h2>
  26. <% } %>
  27. ```
  28. Try EJS online at: https://ionicabizau.github.io/ejs-playground/.
  29. ## Usage
  30. ```javascript
  31. let template = ejs.compile(str, options);
  32. template(data);
  33. // => Rendered HTML string
  34. ejs.render(str, data, options);
  35. // => Rendered HTML string
  36. ejs.renderFile(filename, data, options, function(err, str){
  37. // str => Rendered HTML string
  38. });
  39. ```
  40. It is also possible to use `ejs.render(dataAndOptions);` where you pass
  41. everything in a single object. In that case, you'll end up with local variables
  42. for all the passed options. However, be aware that your code could break if we
  43. add an option with the same name as one of your data object's properties.
  44. Therefore, we do not recommend using this shortcut.
  45. ## Options
  46. - `cache` Compiled functions are cached, requires `filename`
  47. - `filename` The name of the file being rendered. Not required if you
  48. are using `renderFile()`. Used by `cache` to key caches, and for includes.
  49. - `root` Set project root for includes with an absolute path (/file.ejs).
  50. - `context` Function execution context
  51. - `compileDebug` When `false` no debug instrumentation is compiled
  52. - `client` When `true`, compiles a function that can be rendered
  53. in the browser without needing to load the EJS Runtime
  54. ([ejs.min.js](https://github.com/mde/ejs/releases/latest)).
  55. - `delimiter` Character to use with angle brackets for open/close
  56. - `debug` Output generated function body
  57. - `strict` When set to `true`, generated function is in strict mode
  58. - `_with` Whether or not to use `with() {}` constructs. If `false`
  59. then the locals will be stored in the `locals` object. Set to `false` in strict mode.
  60. - `destructuredLocals` An array of local variables that are always destructured from
  61. the locals object, available even in strict mode.
  62. - `localsName` Name to use for the object storing local variables when not using
  63. `with` Defaults to `locals`
  64. - `rmWhitespace` Remove all safe-to-remove whitespace, including leading
  65. and trailing whitespace. It also enables a safer version of `-%>` line
  66. slurping for all scriptlet tags (it does not strip new lines of tags in
  67. the middle of a line).
  68. - `escape` The escaping function used with `<%=` construct. It is
  69. used in rendering and is `.toString()`ed in the generation of client functions.
  70. (By default escapes XML).
  71. - `outputFunctionName` Set to a string (e.g., 'echo' or 'print') for a function to print
  72. output inside scriptlet tags.
  73. - `async` When `true`, EJS will use an async function for rendering. (Depends
  74. on async/await support in the JS runtime.
  75. This project uses [JSDoc](http://usejsdoc.org/). For the full public API
  76. documentation, clone the repository and run `npm run doc`. This will run JSDoc
  77. with the proper options and output the documentation to `out/`. If you want
  78. the both the public & private API docs, run `npm run devdoc` instead.
  79. ## Tags
  80. - `<%` 'Scriptlet' tag, for control-flow, no output
  81. - `<%_` 'Whitespace Slurping' Scriptlet tag, strips all whitespace before it
  82. - `<%=` Outputs the value into the template (escaped)
  83. - `<%-` Outputs the unescaped value into the template
  84. - `<%#` Comment tag, no execution, no output
  85. - `<%%` Outputs a literal '<%'
  86. - `%%>` Outputs a literal '%>'
  87. - `%>` Plain ending tag
  88. - `-%>` Trim-mode ('newline slurp') tag, trims following newline
  89. - `_%>` 'Whitespace Slurping' ending tag, removes all whitespace after it
  90. For the full syntax documentation, please see [docs/syntax.md](https://github.com/mde/ejs/blob/master/docs/syntax.md).
  91. ## Includes
  92. Includes either have to be an absolute path, or, if not, are assumed as
  93. relative to the template with the `include` call. For example if you are
  94. including `./views/user/show.ejs` from `./views/users.ejs` you would
  95. use `<%- include('user/show') %>`.
  96. You must specify the `filename` option for the template with the `include`
  97. call unless you are using `renderFile()`.
  98. You'll likely want to use the raw output tag (`<%-`) with your include to avoid
  99. double-escaping the HTML output.
  100. ```ejs
  101. <ul>
  102. <% users.forEach(function(user){ %>
  103. <%- include('user/show', {user: user}) %>
  104. <% }); %>
  105. </ul>
  106. ```
  107. Includes are inserted at runtime, so you can use variables for the path in the
  108. `include` call (for example `<%- include(somePath) %>`). Variables in your
  109. top-level data object are available to all your includes, but local variables
  110. need to be passed down.
  111. NOTE: Include preprocessor directives (`<% include user/show %>`) are
  112. still supported.
  113. ## Custom delimiters
  114. Custom delimiters can be applied on a per-template basis, or globally:
  115. ```javascript
  116. let ejs = require('ejs'),
  117. users = ['geddy', 'neil', 'alex'];
  118. // Just one template
  119. ejs.render('<?= users.join(" | "); ?>', {users: users}, {delimiter: '?'});
  120. // => 'geddy | neil | alex'
  121. // Or globally
  122. ejs.delimiter = '$';
  123. ejs.render('<$= users.join(" | "); $>', {users: users});
  124. // => 'geddy | neil | alex'
  125. ```
  126. ## Caching
  127. EJS ships with a basic in-process cache for caching the intermediate JavaScript
  128. functions used to render templates. It's easy to plug in LRU caching using
  129. Node's `lru-cache` library:
  130. ```javascript
  131. let ejs = require('ejs'),
  132. LRU = require('lru-cache');
  133. ejs.cache = LRU(100); // LRU cache with 100-item limit
  134. ```
  135. If you want to clear the EJS cache, call `ejs.clearCache`. If you're using the
  136. LRU cache and need a different limit, simple reset `ejs.cache` to a new instance
  137. of the LRU.
  138. ## Custom file loader
  139. The default file loader is `fs.readFileSync`, if you want to customize it, you can set ejs.fileLoader.
  140. ```javascript
  141. let ejs = require('ejs');
  142. let myFileLoad = function (filePath) {
  143. return 'myFileLoad: ' + fs.readFileSync(filePath);
  144. };
  145. ejs.fileLoader = myFileLoad;
  146. ```
  147. With this feature, you can preprocess the template before reading it.
  148. ## Layouts
  149. EJS does not specifically support blocks, but layouts can be implemented by
  150. including headers and footers, like so:
  151. ```ejs
  152. <%- include('header') -%>
  153. <h1>
  154. Title
  155. </h1>
  156. <p>
  157. My page
  158. </p>
  159. <%- include('footer') -%>
  160. ```
  161. ## Client-side support
  162. Go to the [Latest Release](https://github.com/mde/ejs/releases/latest), download
  163. `./ejs.js` or `./ejs.min.js`. Alternately, you can compile it yourself by cloning
  164. the repository and running `jake build` (or `$(npm bin)/jake build` if jake is
  165. not installed globally).
  166. Include one of these files on your page, and `ejs` should be available globally.
  167. ### Example
  168. ```html
  169. <div id="output"></div>
  170. <script src="ejs.min.js"></script>
  171. <script>
  172. let people = ['geddy', 'neil', 'alex'],
  173. html = ejs.render('<%= people.join(", "); %>', {people: people});
  174. // With jQuery:
  175. $('#output').html(html);
  176. // Vanilla JS:
  177. document.getElementById('output').innerHTML = html;
  178. </script>
  179. ```
  180. ### Caveats
  181. Most of EJS will work as expected; however, there are a few things to note:
  182. 1. Obviously, since you do not have access to the filesystem, `ejs.renderFile()` won't work.
  183. 2. For the same reason, `include`s do not work unless you use an `include callback`. Here is an example:
  184. ```javascript
  185. let str = "Hello <%= include('file', {person: 'John'}); %>",
  186. fn = ejs.compile(str, {client: true});
  187. fn(data, null, function(path, d){ // include callback
  188. // path -> 'file'
  189. // d -> {person: 'John'}
  190. // Put your code here
  191. // Return the contents of file as a string
  192. }); // returns rendered string
  193. ```
  194. See the [examples folder](https://github.com/mde/ejs/tree/master/examples) for more details.
  195. ### IDE Integration with Syntax Highlighting
  196. VSCode:Javascript EJS by *DigitalBrainstem*
  197. ## Related projects
  198. There are a number of implementations of EJS:
  199. * TJ's implementation, the v1 of this library: https://github.com/tj/ejs
  200. * Jupiter Consulting's EJS: http://www.embeddedjs.com/
  201. * EJS Embedded JavaScript Framework on Google Code: https://code.google.com/p/embeddedjavascript/
  202. * Sam Stephenson's Ruby implementation: https://rubygems.org/gems/ejs
  203. * Erubis, an ERB implementation which also runs JavaScript: http://www.kuwata-lab.com/erubis/users-guide.04.html#lang-javascript
  204. * DigitalBrainstem EJS Language support: https://github.com/Digitalbrainstem/ejs-grammar
  205. ## License
  206. Licensed under the Apache License, Version 2.0
  207. (<http://www.apache.org/licenses/LICENSE-2.0>)
  208. - - -
  209. EJS Embedded JavaScript templates copyright 2112
  210. mde@fleegix.org.