How to Customize Lodash Template Delimiters

Lodash’s _.template utility allows developers to compile JavaScript templates using customizable regular expressions for delimiter syntax. By default, Lodash uses ERB-style tags, but it provides built-in configuration properties to customize three core delimiters: evaluate, interpolate, and escape. This article breaks down each customizable delimiter property, explains how they function, and demonstrates how to configure them globally or per template.


The Three Customizable Delimiters

Lodash controls delimiter matching via regular expressions defined either globally on _.templateSettings or locally via the options argument in _.template(string, [options]).

1. Interpolate (interpolate)

2. Escape (escape)

3. Evaluate (evaluate)


How to Apply Custom Delimiters

You can configure delimiters in two ways: globally for all templates or locally for a single template instance.

Global Configuration

Modify _.templateSettings directly to change the default syntax across your entire application:

// Switch to Mustache/Twig style delimiters globally
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
_.templateSettings.escape = /{{-([\s\S]+?)}}/g;
_.templateSettings.evaluate = /{%\s*([\s\S]+?)\s*%}/g;

// Compiling using the new global delimiters
const compiled = _.template('Hello {{ user }}! {% if (isAdmin) { %} {{- adminTag }} {% } %}');

const output = compiled({
  user: 'Alex',
  isAdmin: true,
  adminTag: '<b>Administrator</b>'
});

Local Configuration

Pass custom delimiter patterns within the optional second parameter of _.template to avoid side effects in other parts of the application:

const templateString = 'Hello ${ name }, role: ${ role }';

const compiled = _.template(templateString, {
  interpolate: /\${([^\\}]+?)}/g
});

const result = compiled({ name: 'Sam', role: 'Developer' });
// Output: "Hello Sam, role: Developer"

Summary of Delimiter Settings

Option Key Default Pattern Purpose
interpolate /<%=([\s\S]+?)%>/g Unescaped variable/expression output
escape /<%-([\s\S]+?)%>/g HTML-escaped variable/expression output
evaluate /<%([\s\S]+?)%>/g JavaScript logic execution (loops, conditionals)