Home Lodash String methods _.template() Lodash _.template() Method Overview
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
Fundamentals
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().
Foundation
📝 Syntax _.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. 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!" Cheat Sheet
⚡ Quick Reference Task Code pattern Result Compile _.template(source)render function Render render({ name: 'A' })filled string Escape HTML use escape tagsSafe text output Custom delim options.interpolateRegExp pattern Reuse const fn = _.template(t)Compile once Modern alt template literalsES6 backticks
Returns functionCallable renderer
Tags 3 kindsinterpolate, escape, evaluate
Security cautionNo user templates
Reference
🧰 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 onlyHands-On
Examples Gallery Practical _.template() patterns with sample output and interactive Try It Yourself labs.
Basic Reuse HTML Email Custom Security 📚 Getting Started Compile and render a simple greeting template.
Example 1 — Basic interpolation Compile a template with a name placeholder and render it.
// interpolate tag: < + %= name + >
const templateString = "Hello, " + "<" + "%= name %" + ">" + "!";
const compiled = _.template(templateString);
const rendered = compiled({ name: "John" });
console.log(rendered);
// -> "Hello, John!" 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.
const tpl = "Hi, " + "<" + "%= name %" + ">" + "!";
const greet = _.template(tpl);
console.log(greet({ name: "Alice" }));
console.log(greet({ name: "Bob" })); 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.
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" }
}); <div class="profile"><h2>Alice</h2><p>Email: alice@example.com</p></div> 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.
const emailTpl = _.template(
"Dear " + "<" + "%= recipient %" + ">,\n" +
"Order ID: " + "<" + "%= orderId %" + ">"
);
const body = emailTpl({ recipient: "Alice", orderId: "123456" }); Dear Alice,
Order ID: 123456 Example 5 — Custom delimiters Use dollar-brace style delimiters via options.
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.
// 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.
Compare
📋 Related operations Topic _.template() ES6 literals UI frameworks Compile step Yes No Component compile Reuse Compiled fn Inline Virtual DOM User source Dangerous N/A Sandboxed patterns Best for Email/HTML snippets Simple strings Interactive 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.
Important
📝 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. Wrap Up
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 What does _.template() do? It compiles a template string into a function. Call the function with a data object to produce the rendered output with variables substituted.
What are interpolate tags? 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.
Is _.template() safe for user input? No if users supply the template source. Compiled templates can execute JavaScript. Only compile trusted template strings; sanitize data values.
How do I escape HTML in output? Use escape tags (default hyphen-percent-equals) for HTML-escaped output, or pre-escape data before interpolation.
Can I customize delimiters? Yes. Pass an options object with interpolate, escape, and evaluate RegExp patterns.
Should I recompile every render? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion