Lodash _.template() Method

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

What You’ll Learn

By the end of this tutorial, you’ll use Lodash’s _.template() confidently in real JavaScript projects.

01

Compile once

_.template(source)

02

Interpolate tags

Insert data values

03

Escape tags

HTML-safe output

04

Data object

Render with { key }

05

Custom delimiters

options regex

06

Security

Trusted sources only

What Is _.template()?

_.template() compiles a string with interpolate tags into a reusable function. Invoke it with a data object to generate emails, HTML snippets, or reports—similar in spirit to ERB or Mustache, but powered by JavaScript.

💡
Beginner tip

Treat template source like application code: store templates in your repo, compile at build or startup, and never pass raw user text into _.template().

📝 Syntax

javascript
_.template(string, [options])

Syntax Rules

  • string — Template source with interpolate / escape / evaluate tags.
  • options — Optional RegExp delimiters and variable name (imports, sourceURL).
  • Return — Function (data) => string.
  • Interpolate — Default tags output escaped values (see Lodash docs).
  • Security — Evaluate tags run JS—disable or avoid for untrusted templates.
javascript
import template from "lodash/template";

// interpolate tags: open + %= name + close
const source = "Hello, " + "<" + "%= name %" + ">" + "!";
const render = template(source);
const output = render({ name: "John" });
// -> "Hello, John!"

⚡ Quick Reference

TaskCode patternResult
Compile_.template(source)render function
Renderrender({ name: 'A' })filled string
Escape HTMLuse escape tagsSafe text output
Custom delimoptions.interpolateRegExp pattern
Reuseconst fn = _.template(t)Compile once
Modern alttemplate literalsES6 backticks
Returns
function

Callable renderer

Tags
3 kinds

interpolate, escape, evaluate

Security
caution

No user templates

Perf
reuse

Compile once

🧰 Parameters

string Required

Template source containing delimiter tags.

_.template(tplSource)
options Optional

interpolate, escape, evaluate RegExps; variable, imports.

{ interpolate: /.../ }
compiled fn Renderer

Call with data object; returns rendered string.

fn({ user: u })
security Critical

Do not compile untrusted template strings.

// fixed templates only

Examples Gallery

Practical _.template() patterns with sample output and interactive Try It Yourself labs.

📚 Getting Started

Compile and render a simple greeting template.

Example 1 — Basic interpolation

Compile a template with a name placeholder and render it.

javascript
// interpolate tag: < + %= name + >
const templateString = "Hello, " + "<" + "%= name %" + ">" + "!";
const compiled = _.template(templateString);
const rendered = compiled({ name: "John" });

console.log(rendered);
// -> "Hello, John!"
Try It Yourself

How It Works

Compile once into a function; pass data object keys matching tag names.

📚 Practical Patterns

Reuse compiled templates and stay safe.

Example 2 — Reuse compiled template

Store the compiled function and call it for many users.

javascript
const tpl = "Hi, " + "<" + "%= name %" + ">" + "!";
const greet = _.template(tpl);

console.log(greet({ name: "Alice" }));
console.log(greet({ name: "Bob" }));
Try It Yourself

How It Works

Avoid recompiling inside loops; one compile, many renders.

Example 3 — HTML snippet generation

Build a small HTML block from a user object.

javascript
const userTpl = _.template(
  "<div class=\"profile\">" +
  "<h2>" + "<" + "%= user.name %" + ">" + "</h2>" +
  "<p>Email: " + "<" + "%= user.email %" + ">" + "</p>" +
  "</div>"
);

const html = userTpl({
  user: { name: "Alice", email: "alice@example.com" }
});
Try It Yourself

How It Works

For production HTML, prefer escape tags or framework templating with auto-escaping.

Example 4 — Email body template

Personalize notification text with order data.

javascript
const emailTpl = _.template(
  "Dear " + "<" + "%= recipient %" + ">,\n" +
  "Order ID: " + "<" + "%= orderId %" + ">"
);

const body = emailTpl({ recipient: "Alice", orderId: "123456" });

Example 5 — Custom delimiters

Use dollar-brace style delimiters via options.

javascript
const src = "Hello, ${ name }!";
const render = _.template(src, {
  interpolate: /\$\{([\s\S]+?)\}/g
});

console.log(render({ name: "Jane" }));
// -> "Hello, Jane!"

📚 Beyond the Basics

Security and modern alternatives.

Example 6 — Security and template literals

Understand risks and when ES6 literals suffice.

javascript
// UNSAFE: never compile user-provided template source
// const bad = _.template(userInput);

// Safe: fixed template + data
const name = "World";
const safe = "Hello, " + name + "!";

How It Works

Use _.template for multi-line reusable templates; use template literals for simple one-offs.

📋 Related operations

Topic_.template()ES6 literalsUI frameworks
Compile stepYesNoComponent compile
ReuseCompiled fnInlineVirtual DOM
User sourceDangerousN/ASandboxed patterns
Best forEmail/HTML snippetsSimple stringsInteractive UI

🧠 How _.template() Works

1

Parse source

Scan template string for delimiter tags.

Parse
2

Generate fn

Build a function with data parameter.

Compile
3

Bind data

Caller passes object with variable values.

Data
=

Render

Execute generated function; return final string.

📝 Notes

  • Never compile untrusted user strings as template source.
  • Default interpolate tags output HTML-escaped values; verify docs for your Lodash version.
  • Evaluate tags execute JavaScript—remove or avoid in user-facing systems.
  • Compile templates once and reuse the function.
  • For rich UI, prefer React/Vue/Svelte over string templates.

Conclusion

_.template() is a practical Lodash string helper. Use the patterns above in your projects and explore the next method in the series.

❓ Frequently Asked Questions

It compiles a template string into a function. Call the function with a data object to produce the rendered output with variables substituted.
Lodash default interpolate tags look like open-percent-equals ... percent-close (e.g. for outputting a name variable). They insert escaped values into the result.
No if users supply the template source. Compiled templates can execute JavaScript. Only compile trusted template strings; sanitize data values.
Use escape tags (default hyphen-percent-equals) for HTML-escaped output, or pre-escape data before interpolation.
Yes. Pass an options object with interpolate, escape, and evaluate RegExp patterns.
Compile once, reuse the function. Recompiling on every render wastes CPU in hot paths.
Did you know?

Never compile untrusted user strings with _.template()—templates are compiled to functions. Use fixed template sources and pass sanitized data only.

Practice _.template() in the Live Editor

Open the Try It editor and run the examples from this tutorial.

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