ejs

repository·main·Indexed 27 days ago

https://github.com/mde/ejs

Embedded JavaScript templates (ejs) is a lightweight templating engine for generating HTML markup using plain JavaScript. It supports both server-side (Node.js) and client-side rendering. Key features include template compilation via ejs.compile, direct rendering with ejs.render and ejs.renderFile, a comprehensive set of template tags for control flow and output, and a full-featured Command Line Interface (CLI) for rendering templates.

Tokens
3.7K
Snippets
11
Records
28
Agent score
89%

What's inside ejs

  1. Pass data to the EJS CLI

    main

    You can provide data for rendering via several methods in the CLI:

    1. Stdin: Pipe JSON data or redirect a file into the command.
    2. Data File: Use the -f flag with a JSON file.
    3. Command-line option: Use the -i flag with a URI-encoded JSON string.
    4. Direct arguments: Pass key-value pairs at the end of the command.
  2. Use EJS in the browser

    main

    To use EJS client-side, include ejs.js or ejs.min.js in your HTML.

    Caveats:

    1. ejs.renderFile() is unavailable because there is no filesystem access.
    2. include calls will not work unless you provide an include callback to the compiled function to resolve paths manually.
    <div id="output"></div>
    <script src="ejs.min.js"></script>
    <script>
      let people = ['geddy', 'neil', 'alex'],
          html = ejs.render('<%= people.join(", "); %>', {people: people});
      // Vanilla JS:
      document.getElementById('output').innerHTML = html;
    </script>
  3. Use the EJS CLI to render templates

    main

    You can render EJS templates from the command line using the ejs command. The basic syntax requires the template file path and can optionally include data variables.

    Syntax: ejs [options ...] template-file [data variables ...]

  4. Configure EJS caching

    main

    EJS includes a basic in-process cache for compiled functions. You can replace this with an LRU cache using libraries like lru-cache.

    To clear the cache, use ejs.clearCache.

    import ejs from 'ejs';
    import { LRUCache } from 'lru-cache';
    
    ejs.cache = LRUCache({max: 100}); // LRU cache with 100-item limit
  5. Use includes in EJS templates

    main

    Includes can be absolute or relative to the template calling them. Use the raw output tag <%- with include to avoid double-escaping HTML.

    Example:

    <ul
      <% users.forEach(function(user){
        %> <%- include('user/show', {user: user}) %> <% 
      }); %>
    </ul>

    Note: Include preprocessor directives (<% include user/show %>) are not supported in v3.0+.

  6. Configure EJS rendering options

    main

    The following options can be passed to render, renderFile, or compile to customize behavior:

    • cache: If true, compiled functions are cached (requires filename).
    • filename: The name of the file being rendered. Used by cache for keys and for resolving includes.
    • root: Set template root(s) for includes with an absolute path. Can be an array.
    • views: An array of paths to use when resolving includes with relative paths.
    • context: Function execution context.
    • compileDebug: When false, no debug instrumentation is compiled.
    • delimiter: Character to use for inner delimiter (default: %).
    • openDelimiter: Character to use for opening delimiter (default: <).
    • closeDelimiter: Character to use for closing delimiter (default: >).
    • debug: Outputs generated function body.
    • strict: When true, generated function is in strict mode.
    • _with: Whether or not to use with() {} constructs. Set to false in strict mode.
    • unsafePrototypeLocals: When true, allows templates to resolve identifiers through the prototype chain of the locals object. (Note: Enabling this disables v6 prototype-pollution mitigation).
    • destructuredLocals: An array of local variables that are always destructured from the locals object.
    • localsName: Name of the object storing local variables when not using with (default: locals).
    • rmWhitespace: Removes safe-to-remove whitespace and enables a safer version of -%> line slurping.
    • escape: The escaping function used with <%= (default: escapes XML).
    • outputFunctionName: String (e.g., 'echo') for a function to print output inside scriptlet tags.
    • async: When true, uses an async function for rendering.
    • includer: Custom function to handle EJS includes. Receives (originalPath, parsedPath) and should return { filename, template }.
  7. Set custom delimiters globally or per-template

    main

    You can change the characters used for template tags. This can be done for a single render call or globally on the ejs object.

    import ejs from 'ejs';
    const 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>'
  8. Customize the file loader

    main

    By default, EJS uses fs.readFileSync. You can override ejs.fileLoader with a custom function to preprocess templates before they are read.

    import ejs from 'ejs';
    
    const myFileLoad = function (filePath) {
      return 'myFileLoad: ' + fs.readFileSync(filePath);
    };
    
    ejs.fileLoader = myFileLoad;
  9. Basic usage of EJS rendering methods

    main

    EJS provides three primary ways to render templates:

    1. ejs.compile(str, options): Compiles a template string into a function. You can then call this function with data to get the rendered string.
    2. ejs.render(str, data, options): Renders a template string directly using the provided data and options.
    3. ejs.renderFile(filename, data, options, callback): Reads a template file from the filesystem and renders it. This method is asynchronous and uses a callback function function(err, str).
    const 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
    });