Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briangonzalez/2472269 to your computer and use it in GitHub Desktop.
Save briangonzalez/2472269 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment