Run LoDash in Context to Change Template Settings

LoDash has _.template function:

Creates a compiled template function that can interpolate data properties in “interpolate” delimiters, HTML-escape interpolated data properties in “escape” delimiters, and execute JavaScript in “evaluate” delimiters. Data properties may be accessed as free variables in the template. If a setting object is provided it takes precedence over _.templateSettings values.

The template settings affect the behavior of LoDash, and due to Node’s module caching, this will affect the entire application. This will likely cause unexpected error, especially you are writing a module or a library, and the application that requires the module will also use LoDash but with a different template setting:

1
SyntaxError: Unexpected token =

The rule of thumb: Don’t do it!

If you are writing a module or a library that will be required by others, do not change the behavior of other third-party modules that will affect the entire application.

This is similar to another rule: Do not check the environment settings in a module or a library. But if you have to do it, run LoDash in context, so the behavior change will be scoped to the module or the script:

Create a pristine lodash function to avoid conflicts caused by modifying the original. - https://lodash.com/docs#runInContext

Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Run LoDash in Context
// =====================
//
// Run LoDash in context in order to change the behavior of template settings.
//
// Use two different template interpolation styles.
'use strict';
// Dependencies
// ------------
//
// Run LoDash as usual.
var _ = require('lodash');
var tmpl = 'Hello <%= name %>!';
// Main
// ----
(function () {
// Run LoDash in a context.
var _ = require('lodash').runInContext();
var tmpl = 'Hello !';
// Use mustache style instead of the default.
//
// Notice: Due to static page generating error, backslashes before each of
// four braces can be removed in the actual JavaScript file.
_.templateSettings.interpolate = /\{\{([\s\S]+?)\}\}/g;
console.log(_.template(tmpl)({ name: 'Foo' }));
})();
// Use the default template style.
console.log(_.template(tmpl)({ name: 'Foo' }));

Execute it:

1
2
3
$ node run-in-context.js
Hello Foo!
Hello Foo!