Override Lodash Template Delimiters Globally
This article explains how to change the default ERB-style delimiters
in Lodash's _.template function globally across your
application. By modifying the _.templateSettings object,
you can replace the standard <% %> tags with
alternative syntaxes, such as Mustache-style {{ }} curly
braces, ensuring consistent template parsing across all compile calls
without passing custom settings every time.
Understanding
_.templateSettings
Lodash controls template parsing rules via the
_.templateSettings object. By default, it uses regular
expressions that mimic ERB/EJS syntax:
interpolate: Matches expressions to be printed verbatim (default:<%=([\s\S]+?)%>).escape: Matches expressions to be HTML-escaped and printed (default:<%-([\s\S]+?)%>).evaluate: Matches code blocks to be evaluated (default:<%([\s\S]+?)%>).
Because _.template references this object directly when
no local options are provided, modifying _.templateSettings
applies the changes to all subsequent _.template
invocations.
Modifying Delimiters Globally
To apply new delimiters globally, import Lodash and update the
regular expression properties on _.templateSettings before
compiling any templates.
Example: Switching to Mustache/Handlebars Syntax
If you prefer {{ value }} for interpolation and
{{{ value }}} or {{- value }} for escaping,
you can configure the regular expressions as follows:
const _ = require('lodash');
// Configure global delimiters
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
_.templateSettings.escape = /{{-([\s\S]+?)}}/g;
_.templateSettings.evaluate = /{%(.*?)/g;
// Compiling without custom options now uses the global settings
const compiled = _.template('Hello {{ user }}!');
console.log(compiled({ user: 'Alex' }));
// Output: Hello Alex!Order of Matching Precedence
When defining custom regular expressions for
interpolate, escape, and
evaluate, ensure that more specific patterns do not
conflict with broader ones.
For instance, if {{- expression }} is used for escaping
and {{ expression }} for interpolation, make sure the
expressions are strict enough so that interpolate does not
inadvertently consume the prefix intended for escape.
Lodash internally checks escape, then
interpolate, and then evaluate.
Resetting Delimiters
If you need to revert to the standard ERB-style delimiters later in
execution, assign the original regular expressions back to
_.templateSettings:
_.templateSettings.interpolate = /<%=([\s\S]+?)%>/g;
_.templateSettings.escape = /<%-([\s\S]+?)%>/g;
_.templateSettings.evaluate = /<%([\s\S]+?)%>/g;