or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-lodash--template

A JavaScript templating engine that compiles template strings into functions for rendering dynamic content with multiple delimiter syntaxes

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/lodash.template@3.6.x

To install, run

npx @tessl/cli install tessl/npm-lodash--template@3.6.0

index.mddocs/

Lodash Template

Lodash Template is a JavaScript templating engine that compiles template strings into functions for rendering dynamic content. It supports multiple template delimiters for interpolation, HTML escaping, and code evaluation, along with ES6 template literal syntax, making it versatile for web applications, static site generators, and any dynamic string generation needs.

Package Information

  • Package Name: lodash.template
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install lodash.template

Core Imports

const template = require('lodash.template');

For ES6/TypeScript:

import template from 'lodash.template';

Basic Usage

const template = require('lodash.template');

// Basic interpolation
const compiled = template('Hello <%= name %>!');
const result = compiled({ name: 'World' });
// => 'Hello World!'

// HTML escaping
const safeTemplate = template('<div><%- userInput %></div>');
const safeResult = safeTemplate({ userInput: '<script>alert("xss")</script>' });
// => '<div>&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;</div>'

Capabilities

Template Compilation

Creates a compiled template function from a template string with various delimiter options and configuration settings.

/**
 * Creates a compiled template function that can interpolate data properties
 * @param {string} [string=''] - The template string
 * @param {Object} [options] - The options object
 * @param {RegExp} [options.escape] - The HTML "escape" delimiter
 * @param {RegExp} [options.evaluate] - The "evaluate" delimiter  
 * @param {Object} [options.imports] - An object to import into the template as free variables
 * @param {RegExp} [options.interpolate] - The "interpolate" delimiter
 * @param {string} [options.sourceURL] - The sourceURL of the template's compiled source
 * @param {string} [options.variable] - The data object variable name
 * @param {Object} [otherOptions] - Enables the legacy options param signature
 * @returns {Function} Returns the compiled template function
 */
function template(string, options, otherOptions);

Template Delimiters:

  • Interpolation: <%= ... %> - Outputs values directly
  • Escaping: <%- ... %> - HTML-escapes and outputs values
  • Evaluation: <% ... %> - Executes JavaScript code
  • ES6 Template: ${ ... } - Alternative interpolation syntax

Usage Examples:

const template = require('lodash.template');

// Interpolation delimiter
const interpolated = template('Hello <%= user %>!');
console.log(interpolated({ user: 'Alice' }));
// => 'Hello Alice!'

// HTML escape delimiter  
const escaped = template('<b><%- value %></b>');
console.log(escaped({ value: '<script>' }));
// => '<b>&lt;script&gt;</b>'

// Evaluate delimiter with loops
const evaluated = template('<% users.forEach(function(user) { %><li><%- user %></li><% }); %>');
console.log(evaluated({ users: ['Alice', 'Bob'] }));
// => '<li>Alice</li><li>Bob</li>'

// Using print function in evaluate blocks
const withPrint = template('<% print("Hello " + name); %>!');
console.log(withPrint({ name: 'World' }));
// => 'Hello World!'

// ES6 template literal syntax
const es6Template = template('Hello ${ user }!');
console.log(es6Template({ user: 'Charlie' }));
// => 'Hello Charlie!'

// Escaping delimiters with backslashes
const escapedTemplate = template('<%= "\\<%- value %\\>" %>');
console.log(escapedTemplate({ value: 'ignored' }));
// => '<%- value %>'

Template Options Configuration

Customize template compilation with delimiter configuration, variable scoping, and import functionality.

interface TemplateOptions {
  /** RegExp pattern for HTML escape delimiters (default: lodash.templateSettings.escape) */
  escape?: RegExp;
  /** RegExp pattern for evaluate delimiters (default: lodash.templateSettings.evaluate) */
  evaluate?: RegExp;
  /** Object containing variables to import into template scope */
  imports?: Object;
  /** RegExp pattern for interpolate delimiters (default: lodash.templateSettings.interpolate) */
  interpolate?: RegExp;
  /** Source URL for debugging compiled templates */
  sourceURL?: string;
  /** Variable name for data object to avoid with-statement usage */
  variable?: string;
}

Usage Examples:

const template = require('lodash.template');

// Custom delimiters
const customTemplate = template('Hello {{ name }}!', {
  interpolate: /\{\{([\s\S]+?)\}\}/g
});
console.log(customTemplate({ name: 'Mustache' }));
// => 'Hello Mustache!'

// Importing external libraries
const compiled = template('<% _.each(users, function(user) { %><li><%- user %></li><% }); %>', {
  imports: { '_': require('lodash') }
});
console.log(compiled({ users: ['Alice', 'Bob'] }));
// => '<li>Alice</li><li>Bob</li>'

// Using variable option to avoid with-statement
const withVariable = template('Hello <%= data.name %>!', {
  variable: 'data'
});
console.log(withVariable({ name: 'TypeScript' }));
// => 'Hello TypeScript!'

// Source URL for debugging
const debugTemplate = template('Hello <%= name %>!', {
  sourceURL: '/templates/greeting.jst'
});
// Template function will have source mapping for debugging

Compiled Template Function

The function returned by template compilation with properties and usage patterns.

interface CompiledTemplate {
  /** 
   * Execute the compiled template with data
   * @param {Object} data - Data object to render template with
   * @returns {string} Rendered template string
   */
  (data?: Object): string;
  
  /** Source code of the compiled template function for inspection */
  source: string;
}

Usage Examples:

const template = require('lodash.template');

// Create and use compiled template
const compiled = template('Name: <%= name %>, Age: <%= age %>');
const result = compiled({ name: 'Alice', age: 30 });
// => 'Name: Alice, Age: 30'

// Access source code for inspection
console.log(compiled.source);
// => 'function(obj) {\n  obj || (obj = {});\n  var __t, __p = \'\';\n...'

// Using the source property for inline template generation
const fs = require('fs');
const path = require('path');
const mainTemplate = template('Hello <%= user %>!');
const jsCode = `
var JST = {
  "greeting": ${mainTemplate.source}
};
`;
// Write compiled template as JavaScript module

// Reuse compiled template with different data
const user1 = compiled({ name: 'Bob', age: 25 });
const user2 = compiled({ name: 'Carol', age: 35 });

Error Handling

Template compilation and execution error handling patterns.

The template function internally handles compilation errors and will throw if compilation fails. For error handling in template execution, use standard JavaScript try/catch blocks.

Usage Examples:

const template = require('lodash.template');

// Handle compilation errors
try {
  const compiled = template('Invalid template: <%= %>');
} catch (error) {
  console.log('Template compilation failed:', error.message);
}

// Handle template execution errors
const compiled = template('<%= data.deeply.nested.value %>');
try {
  const result = compiled({ data: {} });
} catch (error) {
  console.log('Template execution failed:', error.message);
}

// Safe template execution with fallback
function safeTemplate(templateStr, data, fallback = '') {
  try {
    const compiled = template(templateStr);
    return compiled(data);
  } catch (error) {
    console.error('Template error:', error.message);
    return fallback;
  }
}

Template Settings Integration

Lodash.template integrates with global template settings for default delimiter configuration.

/**
 * Global template settings object (via lodash.templatesettings dependency)
 */
interface TemplateSettings {
  /** Default RegExp for escape delimiters */
  escape: RegExp;
  /** Default RegExp for evaluate delimiters */
  evaluate: RegExp;
  /** Default RegExp for interpolate delimiters */
  interpolate: RegExp;
  /** Default imports object for template scope */
  imports: {
    _: Object; // lodash utilities
  };
}

Usage Examples:

const template = require('lodash.template');
const templateSettings = require('lodash.templatesettings');

// Modify global template settings
templateSettings.interpolate = /\{\{([\s\S]+?)\}\}/g;

// Templates created after this will use new delimiters by default
const compiled = template('Hello {{ name }}!');
console.log(compiled({ name: 'Global' }));
// => 'Hello Global!'

// Individual templates can still override global settings
const customCompiled = template('Hello <%= name %>!', {
  interpolate: /<%=([\s\S]+?)%>/g
});

Advanced Features

Template Compilation Process

Understanding the internal compilation process for advanced usage patterns.

  1. Input Processing: Template strings are normalized and options are merged with global settings
  2. Delimiter Compilation: Regular expressions are created to match template delimiters
  3. Source Generation: Template string is parsed and JavaScript function source is generated
  4. Function Creation: Function constructor creates executable template with proper scope
  5. Error Handling: Compilation errors are caught and wrapped in Error objects

Security Considerations

  • HTML Escaping: Use <%- delimiters to prevent XSS attacks when outputting user data
  • Code Injection: Evaluate delimiters <% execute arbitrary JavaScript - validate template sources
  • Variable Scoping: Use variable option to avoid with statements and improve security
  • Import Safety: Be cautious when providing external libraries via imports option

Performance Optimization

  • Pre-compilation: Compile templates once and reuse with different data
  • Source Caching: Store compiled template functions to avoid repeated compilation
  • Variable Scoping: Use variable option for better performance and security
  • Import Management: Minimize imports object size for faster template execution

Browser Compatibility

  • Designed primarily for Node.js environments
  • Requires CommonJS module system
  • No browser-specific APIs used in core functionality
  • Can be bundled for browser use with appropriate module bundlers