Skip to content

Instantly share code, notes, and snippets.

@brianarn
Created May 4, 2010 22:37
Show Gist options
  • Save brianarn/390136 to your computer and use it in GitHub Desktop.
Save brianarn/390136 to your computer and use it in GitHub Desktop.
Conditionals with underscore.js
// A means of using underscore.js to do templates with conditionals
// Inside of underscore's template, it returns a function that uses
// 'with' on a variable named obj, and you can touch into that using
// inline JS and <% %> wrappers
// A template with conditional display of last names:
var good = _.template("Hello: <%= name %> <% if (obj.lastname) { %> <%= lastname %> <% } %>");
// A template that tries to do that, but fails:
var bad = _.template("Hello: <%= name %> <% if (lastname) { %> <%= lastname %> <% } %>");
// The second approach doesn't fail initially, but will throw a
// 'lastname is not defined' error when you try to use the template.
// It's ugly, but it works.
@sndrs
Copy link

sndrs commented Nov 16, 2011

perfect, thanks!

@kylewelsby
Copy link

Quick and concise. Thanks

@atlcell
Copy link

atlcell commented Oct 15, 2013

Great

@felipepastor
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment