You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

271 lines
9.3 KiB

  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-square)](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. ```html
  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. - `localsName` Name to use for the object storing local variables when not using
  61. `with` Defaults to `locals`
  62. - `rmWhitespace` Remove all safe-to-remove whitespace, including leading
  63. and trailing whitespace. It also enables a safer version of `-%>` line
  64. slurping for all scriptlet tags (it does not strip new lines of tags in
  65. the middle of a line).
  66. - `escape` The escaping function used with `<%=` construct. It is
  67. used in rendering and is `.toString()`ed in the generation of client functions.
  68. (By default escapes XML).
  69. - `outputFunctionName` Set to a string (e.g., 'echo' or 'print') for a function to print
  70. output inside scriptlet tags.
  71. - `async` When `true`, EJS will use an async function for rendering. (Depends
  72. on async/await support in the JS runtime.
  73. This project uses [JSDoc](http://usejsdoc.org/). For the full public API
  74. documentation, clone the repository and run `npm run doc`. This will run JSDoc
  75. with the proper options and output the documentation to `out/`. If you want
  76. the both the public & private API docs, run `npm run devdoc` instead.
  77. ## Tags
  78. - `<%` 'Scriptlet' tag, for control-flow, no output
  79. - `<%_` 'Whitespace Slurping' Scriptlet tag, strips all whitespace before it
  80. - `<%=` Outputs the value into the template (escaped)
  81. - `<%-` Outputs the unescaped value into the template
  82. - `<%#` Comment tag, no execution, no output
  83. - `<%%` Outputs a literal '<%'
  84. - `%%>` Outputs a literal '%>'
  85. - `%>` Plain ending tag
  86. - `-%>` Trim-mode ('newline slurp') tag, trims following newline
  87. - `_%>` 'Whitespace Slurping' ending tag, removes all whitespace after it
  88. For the full syntax documentation, please see [docs/syntax.md](https://github.com/mde/ejs/blob/master/docs/syntax.md).
  89. ## Includes
  90. Includes either have to be an absolute path, or, if not, are assumed as
  91. relative to the template with the `include` call. For example if you are
  92. including `./views/user/show.ejs` from `./views/users.ejs` you would
  93. use `<%- include('user/show') %>`.
  94. You must specify the `filename` option for the template with the `include`
  95. call unless you are using `renderFile()`.
  96. You'll likely want to use the raw output tag (`<%-`) with your include to avoid
  97. double-escaping the HTML output.
  98. ```html
  99. <ul>
  100. <% users.forEach(function(user){ %>
  101. <%- include('user/show', {user: user}) %>
  102. <% }); %>
  103. </ul>
  104. ```
  105. Includes are inserted at runtime, so you can use variables for the path in the
  106. `include` call (for example `<%- include(somePath) %>`). Variables in your
  107. top-level data object are available to all your includes, but local variables
  108. need to be passed down.
  109. NOTE: Include preprocessor directives (`<% include user/show %>`) are
  110. still supported.
  111. ## Custom delimiters
  112. Custom delimiters can be applied on a per-template basis, or globally:
  113. ```javascript
  114. let ejs = require('ejs'),
  115. users = ['geddy', 'neil', 'alex'];
  116. // Just one template
  117. ejs.render('<?= users.join(" | "); ?>', {users: users}, {delimiter: '?'});
  118. // => 'geddy | neil | alex'
  119. // Or globally
  120. ejs.delimiter = '$';
  121. ejs.render('<$= users.join(" | "); $>', {users: users});
  122. // => 'geddy | neil | alex'
  123. ```
  124. ## Caching
  125. EJS ships with a basic in-process cache for caching the intermediate JavaScript
  126. functions used to render templates. It's easy to plug in LRU caching using
  127. Node's `lru-cache` library:
  128. ```javascript
  129. let ejs = require('ejs'),
  130. LRU = require('lru-cache');
  131. ejs.cache = LRU(100); // LRU cache with 100-item limit
  132. ```
  133. If you want to clear the EJS cache, call `ejs.clearCache`. If you're using the
  134. LRU cache and need a different limit, simple reset `ejs.cache` to a new instance
  135. of the LRU.
  136. ## Custom file loader
  137. The default file loader is `fs.readFileSync`, if you want to customize it, you can set ejs.fileLoader.
  138. ```javascript
  139. let ejs = require('ejs');
  140. let myFileLoad = function (filePath) {
  141. return 'myFileLoad: ' + fs.readFileSync(filePath);
  142. };
  143. ejs.fileLoader = myFileLoad;
  144. ```
  145. With this feature, you can preprocess the template before reading it.
  146. ## Layouts
  147. EJS does not specifically support blocks, but layouts can be implemented by
  148. including headers and footers, like so:
  149. ```html
  150. <%- include('header') -%>
  151. <h1>
  152. Title
  153. </h1>
  154. <p>
  155. My page
  156. </p>
  157. <%- include('footer') -%>
  158. ```
  159. ## Client-side support
  160. Go to the [Latest Release](https://github.com/mde/ejs/releases/latest), download
  161. `./ejs.js` or `./ejs.min.js`. Alternately, you can compile it yourself by cloning
  162. the repository and running `jake build` (or `$(npm bin)/jake build` if jake is
  163. not installed globally).
  164. Include one of these files on your page, and `ejs` should be available globally.
  165. ### Example
  166. ```html
  167. <div id="output"></div>
  168. <script src="ejs.min.js"></script>
  169. <script>
  170. let people = ['geddy', 'neil', 'alex'],
  171. html = ejs.render('<%= people.join(", "); %>', {people: people});
  172. // With jQuery:
  173. $('#output').html(html);
  174. // Vanilla JS:
  175. document.getElementById('output').innerHTML = html;
  176. </script>
  177. ```
  178. ### Caveats
  179. Most of EJS will work as expected; however, there are a few things to note:
  180. 1. Obviously, since you do not have access to the filesystem, `ejs.renderFile()` won't work.
  181. 2. For the same reason, `include`s do not work unless you use an `include callback`. Here is an example:
  182. ```javascript
  183. let str = "Hello <%= include('file', {person: 'John'}); %>",
  184. fn = ejs.compile(str, {client: true});
  185. fn(data, null, function(path, d){ // include callback
  186. // path -> 'file'
  187. // d -> {person: 'John'}
  188. // Put your code here
  189. // Return the contents of file as a string
  190. }); // returns rendered string
  191. ```
  192. See the [examples folder](https://github.com/mde/ejs/tree/master/examples) for more details.
  193. ### IDE Integration with Syntax Highlighting
  194. VSCode:Javascript EJS by *DigitalBrainstem*
  195. ## Related projects
  196. There are a number of implementations of EJS:
  197. * TJ's implementation, the v1 of this library: https://github.com/tj/ejs
  198. * Jupiter Consulting's EJS: http://www.embeddedjs.com/
  199. * EJS Embedded JavaScript Framework on Google Code: https://code.google.com/p/embeddedjavascript/
  200. * Sam Stephenson's Ruby implementation: https://rubygems.org/gems/ejs
  201. * Erubis, an ERB implementation which also runs JavaScript: http://www.kuwata-lab.com/erubis/users-guide.04.html#lang-javascript
  202. * DigitalBrainstem EJS Language support: https://github.com/Digitalbrainstem/ejs-grammar
  203. ## License
  204. Licensed under the Apache License, Version 2.0
  205. (<http://www.apache.org/licenses/LICENSE-2.0>)
  206. - - -
  207. EJS Embedded JavaScript templates copyright 2112
  208. mde@fleegix.org.