Created
May 4, 2010 22:37
-
-
Save brianarn/390136 to your computer and use it in GitHub Desktop.
Conditionals with underscore.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. |
Quick and concise. Thanks
Great
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
perfect, thanks!