Lodash _.templateSettings.evaluate

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 configure Lodash’s evaluate RegExp and write conditionals and loops inside _.template() source.

01

Logic tags

Default ERB-style blocks for if/else and loops (no equals sign).

02

vs interpolate

evaluate runs code; interpolate prints values.

03

obj prefix

Reference data as obj.loggedIn with default settings.

04

RegExp rules

Capture group, non-greedy match, and global flag.

05

Per-template override

Pass custom evaluate in the options object.

06

Security

Compile trusted template source only—logic tags run JavaScript.

What Is _.templateSettings.evaluate?

_.templateSettings.evaluate is a RegExp that marks sections of template source containing JavaScript logic—if/else branches, loops, and other statements that control what gets rendered. Unlike interpolate tags, evaluate blocks do not automatically insert their return value into the output string.

💡
Beginner tip

Think of evaluate as “run this JavaScript inside the template.” Pair it with interpolate tags to print values inside branches: open a logic block, write static text or an interpolate tag, then close the block.

The default delimiter family matches ERB logic tags (open-percent without equals). You customize evaluate when you need different syntax while keeping interpolate on Mustache braces or another style.

📝 Syntax

Assign a RegExp to the global settings object (or pass it per compile):

javascript
_.templateSettings.evaluate = /PATTERN/g;

// Default Lodash logic-tag pattern:
// /<%([\s\S]+?)%>/g

Syntax Rules

  • Type — must be a RegExp, never a function.
  • Capture group — group 1 holds the JavaScript statement(s) Lodash embeds in the compiled function.
  • No automatic output — unlike interpolate, evaluate code does not print by default; use interpolate tags for visible values.
  • Data access — use obj.field (or your variable name) inside blocks.
  • Compile time — Lodash reads the pattern when _.template() runs.
javascript
import template from "lodash/template";

const tpl = template(
  "<% if (obj.loggedIn) { %>Welcome, <%= obj.username %>!<% } else { %>" +
  "Please log in.<% } %>"
);

console.log(tpl({ loggedIn: true, username: "John" }));
// -> "Welcome, John!"

⚡ Quick Reference

Tag roleSettingTypical use
Logic / control flowevaluateif/else, loops, local vars
Value outputinterpolatePrint obj.name
Escaped outputescapeHTML-safe insertion
Default evaluate/<%([\s\S]+?)%>/gERB logic blocks
Per-template_.template(str, { evaluate: /.../g })One-off delimiter style
Helpers in logicimports_.forEach(obj.items, ...)
Default
/<%...%>/g

Logic delimiters

Type
RegExp

Not a function

Output
none

Use interpolate

Sibling
interpolate

Value tags

🧰 Property Details

How evaluate fits into _.templateSettings:

evaluate RegExp

Pattern matching logic and control-flow tags. Captured JavaScript is emitted into the compiled render function body.

/<%([\s\S]+?)%>/g
capture group 1 Statements

JavaScript inside delimiters—e.g. if (obj.ok) {, obj.items.forEach(function (item) {, }.

if (obj.premium) {
with interpolate Pair tags

Logic blocks wrap static text and interpolate tags that produce visible output between evaluate segments.

... <%= obj.name %> ...
per-compile override Optional

Pass { evaluate: /.../g } to _.template() without changing global settings.

_.template(str, { evaluate })

All three delimiter RegExps—evaluate, interpolate, and escape—are scanned when Lodash parses template source. Keep their syntax distinct so tags are not ambiguous.

Examples Gallery

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

📚 Getting Started

Conditional greeting with default evaluate delimiters.

Example 1 — if/else welcome message

Branch on obj.loggedIn and print the username with an interpolate tag inside the true branch.

javascript
const tpl = _.template(
  "<% if (obj.loggedIn) { %>Welcome, <%= obj.username %>!<% } else { %>" +
  "Please log in.<% } %>"
);

console.log(tpl({ loggedIn: true, username: "John" }));
// -> "Welcome, John!"

console.log(tpl({ loggedIn: false }));
// -> "Please log in."
Try It Yourself

How It Works

Evaluate tags compile to real JavaScript if statements. Interpolate tags between them insert dynamic values into the final string.

Example 2 — Default evaluate pattern

Lodash ships with the standard logic-tag RegExp—no change required for ERB-style templates.

javascript
// Already set by default:
// _.templateSettings.evaluate === /<%([\s\S]+?)%>/g

const tpl = _.template(
  "<% if (obj.count > 0) { %>You have <%= obj.count %> items.<% } %>"
);

console.log(tpl({ count: 3 }));
// -> "You have 3 items."

📈 Practical Patterns

Loops, role checks, and hybrid delimiter setups.

Example 3 — Loop with obj.users

Iterate an array inside evaluate blocks and output each name with interpolate tags.

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

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

How It Works

Or use _.forEach from imports for the same pattern with Lodash iteration helpers.

Example 4 — Role-based message

Show different copy when obj.isAdmin is true.

javascript
const accessTpl = _.template(
  "<% if (obj.isAdmin) { %>Welcome, admin!<% } else { %>Access denied.<% } %>"
);

console.log(accessTpl({ isAdmin: true }));
// -> "Welcome, admin!"
Try It Yourself

Example 5 — Per-template evaluate override

Keep global defaults but pass a custom logic delimiter for one compile.

javascript
const customTpl = _.template(
  "[[ if (obj.ready) { ]]Go![[ } else { ]]Wait.[[ } ]]",
  { evaluate: /\[\[([\s\S]+?)\]\]/g }
);

console.log(customTpl({ ready: true }));
// -> "Go!"

🚀 Beyond the Basics

Mustache output with ERB logic—a common hybrid.

Example 6 — Mustache interpolate + default evaluate

Change only interpolate to {{ }}; keep evaluate on ERB logic tags.

javascript
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
// evaluate stays default

const tpl = _.template(
  "<% if (obj.premium) { %>Welcome, {{ obj.name }}! (Premium)<% } else { %>" +
  "Hello, {{ obj.name }}.<% } %>"
);

console.log(tpl({ name: "Alex", premium: true }));
// -> "Welcome, Alex! (Premium)"

When to customize evaluate

Most projects leave evaluate on the default ERB logic tags and only customize interpolate or escape. Change evaluate when your template grammar requires distinct logic delimiters.

🧠 How evaluate Works

1

Load evaluate RegExp

_.template() reads evaluate from global settings or per-call options.

Config
2

Parse template segments

Lodash splits source by evaluate, interpolate, and escape patterns into static strings and code chunks.

Parse
3

Embed logic in render fn

Captured evaluate code becomes statements in the compiled function—real if/else and loops at runtime.

Compile
=

Control output shape

Logic decides which static text and interpolate segments run; the final string reflects those branches.

📝 Notes

  • evaluate must be a RegExp, not a function.
  • Logic tags do not print values automatically—use interpolate for output.
  • Reference data as obj.field unless you renamed variable.
  • Changes apply at compile time; recompile after editing the pattern.
  • Never compile template source from untrusted users—evaluate blocks execute JavaScript.
  • Keep evaluate, interpolate, and escape delimiters visually distinct to avoid parse ambiguity.

Conclusion

_.templateSettings.evaluate defines which delimiters wrap logic and control flow in Lodash templates. Use it for if/else, loops, and branching while interpolate handles the values users see.

Most teams keep the default ERB logic tags, customize interpolate when needed, and move on to imports for helpers like _.forEach.

💡 Best Practices

✅ Do

  • Keep logic in evaluate blocks and values in interpolate tags
  • Use obj. prefix consistently for render data
  • Document delimiter choices alongside interpolate and escape settings
  • Prefer precomputing complex data in JavaScript when templates grow large
  • Recompile templates after changing the evaluate RegExp

❌ Don’t

  • Assign a function to templateSettings.evaluate
  • Expect evaluate blocks to print values without interpolate tags
  • Use bare property names like loggedIn when variable is obj
  • Compile untrusted template strings from user input
  • Overlap evaluate and interpolate delimiters so tags become ambiguous

Key Takeaways

Knowledge Unlocked

Five things to remember about evaluate

Use these points when adding logic to Lodash templates.

5
Core concepts
📝 02

No auto print

Use interpolate.

Key rule
🔄 03

if / loops

Control flow in tags.

Pattern
📦 04

obj.*

Default data prefix.

Data
🔒 05

Trusted source

Logic runs as JS.

Security

❓ Frequently Asked Questions

It is a RegExp that tells _.template() which tags contain JavaScript logic to execute without directly printing output. The default pattern matches ERB-style logic tags (open-percent, no equals sign).
A RegExp. Lodash uses it at compile time to find control-flow blocks. Do not assign a callback function to evaluate.
interpolate tags evaluate an expression and insert the result into the output string. evaluate tags run JavaScript for side effects—conditionals, loops, variable setup—without automatically printing a value.
By default Lodash uses a RegExp matching open-percent ... close-percent tags (the form used for if blocks and loops, without the equals sign used by interpolate).
With the default variable setting (obj), yes—write obj.loggedIn and obj.users inside evaluate blocks, not bare loggedIn.
At compile time. Change templateSettings.evaluate before calling _.template(). Already-compiled render functions keep the pattern from when they were built.
Did you know?

Lodash templates borrow ERB’s three-tag model from Ruby on Rails: logic tags (evaluate), value tags (interpolate), and escape tags (escape). That split keeps control flow separate from what gets printed.

Practice evaluate logic in the Live Editor

Build if/else greetings and user lists with control-flow tags.

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