Lodash _.templateSettings.imports

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 6 Examples + 3 Try It
Template configuration

What You’ll Learn

By the end of this tutorial, you’ll know how to inject Lodash and custom helpers into _.template() scope using the imports object.

01

Default _

Call Lodash helpers like _.upperCase() inside template tags.

02

Custom helpers

Add formatPrice, formatDate, or other project utilities.

03

Evaluate blocks

Use _.forEach in logic tags to build HTML lists.

04

Per-template scope

Pass an imports object in the second argument to _.template().

05

Pair with variable

Keep data on obj (or data) and helpers on _.

06

Trusted helpers only

Inject functions you control—never user-supplied code.

What Is _.templateSettings.imports?

_.templateSettings.imports is an object whose properties become local variables inside compiled template functions. The most common entry is _, which exposes the Lodash library so you can write <%= _.max(obj.scores) %> or <% _.forEach(obj.users, function (u) { %> directly in template source.

💡
Beginner tip

Think of imports as “what helpers exist inside my template.” Your render data still comes from the argument you pass to the compiled function—that is controlled separately by variable.

Beyond Lodash, teams add formatters, i18n helpers, or URL builders to imports so templates stay declarative without duplicating utility logic in every tag expression.

📝 Syntax

Assign properties on the global settings object or pass them per compile:

javascript
_.templateSettings.imports._ = _;

// Add a custom helper:
_.templateSettings.imports.formatPrice = function (n) {
  return "$" + n.toFixed(2);
};

Syntax Rules

  • Type — plain object mapping string keys to functions, values, or libraries.
  • Default — Lodash often pre-populates _ in browser builds; set it explicitly in Node.
  • Template usage — reference imported names directly in tag expressions: _.join(...), formatPrice(...).
  • Data vs imports — render data uses obj (or your variable name); helpers live on imports.
  • Compile time — Lodash merges imports when building the render function.
javascript
import template from "lodash/template";

_.templateSettings.imports._ = _;

const tpl = template("The square root of 25 is <%= _.sqrt(25) %>.");
console.log(tpl());
// -> "The square root of 25 is 5"

⚡ Quick Reference

Taskimports setupTemplate usage
Expose Lodashimports._ = _<%= _.upperCase(obj.name) %>
Custom formatterimports.formatPrice = fn<%= formatPrice(obj.total) %>
Loop in templateimports._ = _<% _.forEach(obj.items, ...) %>
Aggregate valuesimports._ = _<%= _.sum(obj.values) %>
Per-template only_.template(str, { imports: { ... } })Scoped to one compile
Merge with defaults_.assign({}, imports, extras)Keep _ while adding helpers
Default key
_

Lodash reference

Type
object

Key-value map

Scope
compile

Baked into render fn

Sibling
variable

Data param name

🧰 Property Details

How imports fits into _.templateSettings:

imports Object

Map of identifiers available inside compiled template code. Keys become variable names in the generated function body.

{ _: _, formatDate: fn }
imports._ Lodash

Standard entry pointing to the Lodash library. Enables _.map, _.filter, _.forEach, and hundreds of other helpers in tags.

imports._ = _
custom keys Optional

Project-specific formatters, constants, or small utilities. Keep them pure and side-effect free when possible.

imports.currency = "USD"
per-compile override Optional

Pass { imports: { helper: fn } } to _.template() to extend or replace imports for one template only.

_.template(str, { imports })

Imported names are separate from the data object (obj by default). Use obj for payload fields and _ / custom imports for reusable logic.

Examples Gallery

Practical imports patterns with copy-ready code, sample output, and interactive Try It Yourself labs.

📚 Getting Started

Expose Lodash in template scope and call a helper from an interpolate tag.

Example 1 — Lodash math with _.sqrt()

Assign Lodash to imports._, then call a utility inside an interpolate tag.

javascript
_.templateSettings.imports._ = _;

const tpl = _.template("The square root of 25 is <%= _.sqrt(25) %>.");
console.log(tpl());
// -> "The square root of 25 is 5"
Try It Yourself

How It Works

Lodash merges imports into the compiled function’s scope. The interpolate tag evaluates _.sqrt(25) as ordinary JavaScript.

Example 2 — Transform render data with _.upperCase()

Combine imports._ with the default obj data parameter.

javascript
_.templateSettings.imports._ = _;

const tpl = _.template("Hello, <%= _.upperCase(obj.name) %>!");
console.log(tpl({ name: "john" }));
// -> "Hello, JOHN!"

📈 Practical Patterns

Custom formatters, HTML list rendering, and per-template helper scopes.

Example 3 — Custom formatPrice helper

Add your own function to imports for reusable formatting logic.

javascript
_.templateSettings.imports.formatPrice = function (amount) {
  return "$" + amount.toFixed(2);
};

const invoiceTpl = _.template(
  "Total due: <%= formatPrice(obj.total) %>"
);

console.log(invoiceTpl({ total: 49.5 }));
// -> "Total due: $49.50"
Try It Yourself

How It Works

Any key on imports becomes a local binding in the compiled template. You call it like a global function inside tag expressions.

Example 4 — Build a list with _.forEach()

Use Lodash inside evaluate blocks to loop over obj.users.

javascript
_.templateSettings.imports._ = _;

const listTpl = _.template(
  "<ul>" +
  "<% _.forEach(obj.users, function (user) { %>" +
  "<li><%= user.name %></li>" +
  "<% }); %>" +
  "</ul>"
);

console.log(listTpl({
  users: [{ name: "Ada" }, { name: "Grace" }]
}));
Try It Yourself

Example 5 — Per-template imports (no global pollution)

Pass helpers only to the template that needs them.

javascript
const badgeTpl = _.template(
  "Status: <%= badge(obj.level) %>",
  {
    imports: {
      badge: function (level) {
        return level === "pro" ? "PRO" : "FREE";
      }
    }
  }
);

console.log(badgeTpl({ level: "pro" }));
// -> "Status: PRO"

🚀 Beyond the Basics

Aggregation helpers and combining imports with data transforms.

Example 6 — Aggregate with _.sum()

Summarize array data passed through obj using an imported Lodash helper.

javascript
_.templateSettings.imports._ = _;

const summaryTpl = _.template(
  "Items: <%= obj.items.length %> | Total: <%= _.sum(obj.items) %>"
);

console.log(summaryTpl({ items: [10, 20, 5] }));
// -> "Items: 3 | Total: 35"

When to precompute instead

For heavy transforms, compute values in JavaScript before rendering and pass simple fields on obj. Reserve imports for small, reusable helpers.

🧠 How imports Works

1

Configure imports object

Set global templateSettings.imports or pass imports in the _.template() options.

Config
2

Compile template source

Lodash builds a function whose body includes bindings for each import key alongside the data parameter.

Compile
3

Reference helpers in tags

Inside interpolate and evaluate tags, call _, formatPrice, or any imported name like normal variables.

Author
=

Render with data object

Pass payload fields on obj; imported helpers stay available on every render call.

📝 Notes

  • imports is an object, not a single function or RegExp.
  • imports._ is the conventional key for Lodash—set it explicitly in Node.js builds.
  • Custom helpers should be trusted code you control, never user callbacks.
  • Imports are fixed at compile time; changing global imports does not update old render functions.
  • Data fields live on obj (or your variable name)—do not confuse with import keys.
  • Keep helpers small; heavy logic belongs in JavaScript before calling the template.

Conclusion

_.templateSettings.imports extends what your templates can call without reimplementing utilities in every tag. Expose Lodash as _, add project formatters, and use per-template overrides when only one file needs a special helper.

Next, configure value delimiters with interpolate, then fine-tune the data parameter name on the variable page.

💡 Best Practices

✅ Do

  • Set imports._ = _ at bootstrap in Node or bundled apps
  • Add small, reusable formatters with clear names like formatPrice
  • Use per-template imports when helpers are template-specific
  • Document available import keys in your template style guide
  • Precompute expensive values in JS when templates get complex

❌ Don’t

  • Inject user-controlled functions into imports
  • Assume _ exists without verifying your build sets it
  • Put render payload data on imports—use the render argument
  • Mutate global imports after compiling shared templates without recompiling
  • Overload templates with business logic better handled outside tags

Key Takeaways

Knowledge Unlocked

Five things to remember about imports

Use these points when extending Lodash template scope.

5
Core concepts
🔧 02

imports._

Lodash in templates.

Default
⚙️ 03

Custom helpers

formatPrice, badge, etc.

Pattern
🔄 04

Per compile

Options.imports override.

Scope
🔒 05

Trusted only

No user functions.

Security

❓ Frequently Asked Questions

It is an object of names and values merged into the scope of compiled template functions. The default includes _ for Lodash when available, so you can call _.upperCase(obj.name) inside template tags.
imports is the whole object. imports._ is one property that holds the Lodash library reference. You can add other keys like formatDate or currency for custom helpers.
Often Lodash sets it automatically in browser builds. Explicitly assigning _.templateSettings.imports._ = _ guarantees _ is available when you compile templates in Node or custom bundles.
Inside interpolate tags (value output), escape tags, and evaluate blocks (logic). Example: an interpolate tag calling _.max(obj.scores), or an evaluate block with _.forEach(obj.items, function(item) { ... }).
Yes. Pass { imports: { formatPrice: fn } } as the second argument to _.template(). Those helpers are available only for that compiled function.
Only inject trusted helpers you wrote or vetted. Template tags execute JavaScript at compile and render time—never expose user-controlled functions through imports.
Did you know?

Lodash’s default templateSettings.imports already reserves a slot for _. Explicitly assigning imports._ = _ is still a good habit in Node.js and custom bundles so templates behave the same everywhere.

Practice template imports in the Live Editor

Call Lodash helpers and custom formatters inside compiled templates.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful