wiradikusuma wiradikusuma - 1 year ago 54
Javascript Question

Making variable optional in underscore.js template

I have this code:

_.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};

var _d = _.template($('#_d').html());

$.get('/foo', function(data) {

and in HTML:

<div id="_d">
{{name}} {{phone}}
<div id="output"></div>

returns something like
, but sometimes it doesn't have
thus simply returns
, which will choke template evaluation thus nothing gets printed in
. How do I make a variable optional?

is beyond my control

Answer Source

The || operator is useful for this sort of thing:

$.get('/foo', function(data) {
    data.phone = data.phone || "";

But since you're already using Underscore, you can use the _.defaults function. This approach is particularly useful for providing defaults for multiple fields:

$.get('/foo', function(data) {
    _.defaults(data, {name : 'joe', phone : ''});