### Install EJS using npm Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Install the EJS package using npm. This is the first step to using EJS with your project. ```sh npm install ejs ``` -------------------------------- ### Basic Express setup with EJS Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Configure Express to use EJS as the view engine and set up a basic route to render an EJS template. Assumes an 'index.ejs' file in a 'views' directory. ```html Hello <%= foo %> ``` ```javascript let express = require('express'); let app = express(); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('index', {foo: 'FOO'}); }); app.listen(4000, () => console.log('Example app listening on port 4000!')); ``` -------------------------------- ### Install EJS using yarn Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Install the EJS package using yarn. This is an alternative to npm for managing project dependencies. ```sh yarn add ejs ``` -------------------------------- ### EJS Template Example Source: https://github.com/mde/ejs/blob/main/README.md A simple EJS template demonstrating conditional rendering based on a user object and displaying the user's name. ```ejs <% if (user) { %>

<%= user.name %>

<% } %> ``` -------------------------------- ### Client-side EJS Rendering Example Source: https://github.com/mde/ejs/blob/main/README.md Include ejs.min.js in your HTML and use the ejs.render function to process templates. The output can be inserted into the DOM using jQuery or vanilla JavaScript. ```html
``` -------------------------------- ### EJS Include Callback Example Source: https://github.com/mde/ejs/blob/main/README.md When using EJS client-side, 'include' directives require a callback function to resolve included file content, as direct filesystem access is not available. ```javascript let str = "Hello <%= include('file', {person: 'John'}); %>", fn = ejs.compile(str); 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 ``` -------------------------------- ### Express Server with EJS Rendering Source: https://github.com/mde/ejs/blob/main/SECURITY.md This snippet demonstrates a basic Express.js server setup that uses EJS for rendering. It highlights a common pattern where user input (req.query) is directly passed to the res.render method, which is flagged as an out-of-scope vulnerability if not handled securely. ```javascript const express = require('express'); const app = express(); const PORT = 3000; app.set('views', __dirname); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('index', req.query); }); app.listen(PORT, ()=> { console.log(`Server is running on ${PORT}`); }); ``` -------------------------------- ### Client-side EJS Rendering Logic Source: https://github.com/mde/ejs/blob/main/examples/client-injection.html This JavaScript code demonstrates how to get an EJS template from the DOM, compile it with data, and inject the resulting HTML into the document's body. Ensure the EJS library is loaded before this script. ```javascript onload = function () { // get the EJS template as a string var templ = document.getElementById('users').innerHTML; console.log('EJS template:'); console.log(templ); // data to output to the template function var data = { names: ['loki', 'tobi', 'jane'] }; // stores the rendered HTML var html = ejs.compile(templ)(data); console.log('Rendered HTML:'); console.log(html); // inject the rendered data to document.body.innerHTML = html; console.log('HTML injected to '); } ``` -------------------------------- ### EJS CLI Custom Delimiter Example Source: https://github.com/mde/ejs/blob/main/README.md Use the -m or --delimiter flag to set a custom character for EJS delimiters. ```shell ./bin/cli.js -m $ ./test/fixtures/user.ejs name=foo ``` -------------------------------- ### EJS Navbar component template Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Example of an EJS template for a reusable navigation bar component. It iterates over a 'links' array to generate list items. ```html ``` -------------------------------- ### Basic EJS Rendering Functions Source: https://github.com/mde/ejs/blob/main/README.md Demonstrates the core functions for compiling and rendering EJS templates. Use `ejs.compile` for pre-compiled templates or `ejs.render` for direct rendering. The `ejs.renderFile` function is used for rendering templates from files. ```javascript 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 }); ``` -------------------------------- ### EJS Layout Implementation Source: https://github.com/mde/ejs/blob/main/README.md Demonstrates a common pattern for implementing layouts in EJS by including header and footer partials. This approach does not use explicit block support. ```ejs <%- include('header') -%>

Title

My page

<%- include('footer') -%> ``` -------------------------------- ### Including EJS Templates Source: https://github.com/mde/ejs/blob/main/README.md Demonstrates how to include another EJS template within a loop, passing local data. Ensure the 'filename' option is set when not using renderFile. ```ejs ``` -------------------------------- ### Custom Delimiters in EJS Source: https://github.com/mde/ejs/blob/main/README.md Demonstrates how to set custom delimiters for EJS templates, either on a per-template basis or globally. Ensure the 'ejs' library is imported. ```javascript import ejs from 'ejs'; const users = ['geddy', 'neil', 'alex']; // Just one template olds.render('

[?= users.join(" | "); ?]

', {users: users}, {delimiter: '?', openDelimiter: '[', closeDelimiter: ']'}); // => '

geddy | neil | alex

' // Or globally ejs.delimiter = '?'; ejs.openDelimiter = '['; ejs.closeDelimiter = ']'; ejs.render('

[?= users.join(" | "); ?]

', {users: users}); // => '

geddy | neil | alex

' ``` -------------------------------- ### Include EJS component in main template Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Demonstrates how to include a separate EJS component (navbar.ejs) into a main EJS template using the `<%- include %>` directive. Also shows how to define JavaScript variables for the component. ```html Homepage <%- include navbar.ejs %> ``` -------------------------------- ### Render EJS template with data from JSON file Source: https://github.com/mde/ejs/blob/main/usage.txt Use this command to render an EJS template using data loaded from a specified JSON file. The `-m` option customizes delimiters. ```bash ejs -m $ ./test/fixtures/user.ejs -f ./user_data.json ``` -------------------------------- ### Set EJS options via app.locals Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Pass EJS options to the view engine by setting them on `app.locals`. Properties matching known EJS options will be passed directly. ```javascript app.locals.delimiter = '?'; ``` -------------------------------- ### Render EJS template to an output file with custom delimiters Source: https://github.com/mde/ejs/blob/main/usage.txt This command renders an EJS template and saves the output to a specified file. It uses custom open and close delimiters. ```bash ejs -p [ -c ] ./template_file.ejs -o ./output.html ``` -------------------------------- ### EJS CLI Data Input via Data File Source: https://github.com/mde/ejs/blob/main/README.md Use the -f or --data-file flag to specify a JSON file containing data for rendering. ```shell $ ejs ./test/fixtures/user.ejs -f ./user_data.json ``` -------------------------------- ### Custom File Loader in EJS Source: https://github.com/mde/ejs/blob/main/README.md Illustrates how to set a custom file loader for EJS, overriding the default 'fs.readFileSync'. This allows for preprocessing templates before they are read. ```javascript import ejs from 'ejs'; const myFileLoad = function (filePath) { return 'myFileLoad: ' + fs.readFileSync(filePath); }; ejs.fileLoader = myFileLoad; ``` -------------------------------- ### EJS CLI Data Input via Arguments Source: https://github.com/mde/ejs/blob/main/README.md Pass data directly at the end of the invocation by specifying key-value pairs. ```shell $ ejs ./test/fixtures/user.ejs name=Lerxst ``` -------------------------------- ### Render EJS template with inline data variables Source: https://github.com/mde/ejs/blob/main/usage.txt Render an EJS template by providing data variables directly on the command line. The `-m` option customizes delimiters. ```bash ejs -m $ ./test/fixtures/user.ejs name=Lerxst ``` -------------------------------- ### EJS Caching with LRUCache Source: https://github.com/mde/ejs/blob/main/README.md Shows how to integrate LRU caching with EJS for intermediate JavaScript functions. Requires the 'lru-cache' library. The cache can be cleared using ejs.clearCache. ```javascript import ejs from 'ejs'; import { LRUCache } from 'lru-cache'; ejs.cache = LRUCache({max: 100}); // LRU cache with 100-item limit ``` -------------------------------- ### Render EJS template removing whitespace and outputting to file Source: https://github.com/mde/ejs/blob/main/usage.txt This command renders an EJS template, removes safe-to-remove whitespace, and writes the result to a specified output file. ```bash ejs -w ./template_with_whitspace.ejs -o ./output_file.html ``` -------------------------------- ### EJS CLI Output Redirection Source: https://github.com/mde/ejs/blob/main/README.md Use the -o or --output-file flag to specify a file for the rendered output instead of stdout. ```shell $ ejs -p [ -c ] ./template_file.ejs -o ./output.html ``` -------------------------------- ### EJS CLI Data Input via Command-line Option Source: https://github.com/mde/ejs/blob/main/README.md Pass JSON data using the -i or --data-input option. The JSON string must be URI-encoded. ```shell ./bin/cli.js -i %7B%22name%22%3A%20%22foo%22%7D ./test/fixtures/user.ejs ``` -------------------------------- ### Set EJS view options using app.set Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Configure EJS options, such as the delimiter, for all views by setting 'view options' in Express. This method is suitable for options that cannot be safely passed with data. ```javascript app.set('view options', {delimiter: '?'}); ``` -------------------------------- ### EJS CLI Data Input via Stdin Source: https://github.com/mde/ejs/blob/main/README.md Pipe JSON data to the EJS CLI for rendering templates. ```shell $ ./test/fixtures/user_data.json | ejs ./test/fixtures/user.ejs ``` ```shell $ ejs ./test/fixtures/user.ejs < test/fixtures/user_data.json ``` -------------------------------- ### Client-Side EJS Compilation Function Source: https://github.com/mde/ejs/blob/main/examples/client-compilation.html This JavaScript function `comp()` retrieves EJS template, locals, and options from HTML elements, compiles the template using `ejs.compile()`, and renders it. It includes error handling for JSON parsing and template execution. ```javascript function comp() { // Get the elements var // input EJS template templ = document.getElementById('input') // JSON locals , locals = document.getElementById('locals') // JSON options , options = document.getElementById('options') // output text area , output = document.getElementById('output') // for dynamic output heading , outputTitle = document.getElementById('output-title') , fn; // Handle errors by catching it, print the message to the output HTML // box, and throwing it again so that it's visible on the JS console. // `stage` sets the corresponding error context. function handleError(func, stage) { try { // Try executing callback func(); } catch (e) { // If there is an exception: // 1. Change output heading to "Error when ..." outputTitle.innerHTML = 'Error ' + stage; // 2. Put the stack trace into the output text area output.textContent = e.stack || e.message || e.toString(); // 3. Rethrow it throw e; } } // Parse options as JSON handleError(function () { options = JSON.parse(options.value || '{}'); }, 'when parsing options'); // Parse locals as JSON handleError(function () { locals = JSON.parse(locals.value || '{}'); }, 'when parsing locals'); // Compile template with specified template and options handleError(function () { fn = ejs.compile(templ.value, options); }, 'when compiling'); // Put the rendered HTML into the output textarea handleError(function () { output.textContent = fn(locals); outputTitle.innerHTML = 'Output HTML'; }, 'when executing template function'); // Note: To get the compiled function source code, use fn.toString() } ``` -------------------------------- ### EJS Template Tags Overview Source: https://github.com/mde/ejs/blob/main/README.md This section lists and describes the different EJS template tags used for scriptlets, outputting values, comments, and whitespace manipulation. ```ejs <% ``` ```ejs <%_ ``` ```ejs <%= ``` ```ejs <%- ``` ```ejs <%# ``` ```ejs <%% ``` ```ejs %%> ``` ```ejs %> ``` ```ejs -%> ``` ```ejs _%> ``` -------------------------------- ### EJS CLI with Strict Mode and Locals Name Source: https://github.com/mde/ejs/blob/main/README.md Use the -n flag for strict mode and -l to specify the name for the locals object when not using 'with'. ```shell $ ejs -n -l _ ./some_template.ejs -f ./data_file.json ``` -------------------------------- ### Render EJS template without 'with' and custom locals name Source: https://github.com/mde/ejs/blob/main/usage.txt Render an EJS template using a specified locals object name for variables and disabling the 'with' statement for strict mode compatibility. Data is loaded from a JSON file. ```bash ejs -n -l _ ./some_template.ejs -f ./data_file.json ``` -------------------------------- ### Import EJS in ES Modules Source: https://github.com/mde/ejs/blob/main/README.md Import the EJS library using the ES Modules syntax. This is suitable for modern JavaScript environments that support ES Modules. ```javascript import ejs from 'ejs'; ``` -------------------------------- ### Pass EJS options with render data Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Include EJS options directly within the data object passed to `res.render`. This requires specifying options for each render call and does not support unsafe options. ```javascript app.get('/', (req, res) => { res.render('index', {foo: 'FOO', delimiter: '?'}); }); ``` -------------------------------- ### Require EJS in CommonJS Source: https://github.com/mde/ejs/blob/main/README.md Require the EJS library using the CommonJS syntax. This is the traditional way to include modules in Node.js. ```javascript const ejs = require('ejs'); ``` -------------------------------- ### Custom EJS render function in Express Source: https://github.com/mde/ejs/wiki/Using-EJS-with-Express Override the default render function in Express to provide custom EJS rendering logic, allowing for specific EJS options to be applied. ```javascript let ejsOptions = {delimiter: '?'}; app.engine('ejs', (path, data, cb) => { ejs.renderFile(path, data, ejsOptions, cb); }); ``` -------------------------------- ### Preventing EJS Vulnerabilities with Input Validation Source: https://github.com/mde/ejs/blob/main/README.md This snippet illustrates a common security pitfall where user input is directly passed to res.render without validation. Always sanitize or validate inputs before rendering to prevent potential vulnerabilities. ```javascript app.get('/', (req, res) => { res.render('index', req.query); }); ``` -------------------------------- ### EJS Template in HTML Source: https://github.com/mde/ejs/blob/main/examples/client-injection.html This is the EJS template embedded within an HTML script tag. It iterates over a 'names' array and displays each name in a list item. ```html <% if (names.length) { %> <% } %> ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.