wiradikusuma wiradikusuma - 13 days ago 5
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) {
$('#output').html(_d(data));
});


and in HTML:

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


/foo
returns something like
{"name":"joe","phone":"12345"}
, but sometimes it doesn't have
phone
thus simply returns
{"name":"joe"}
, which will choke template evaluation thus nothing gets printed in
output
. How do I make a variable optional?

EDIT:
/foo
is beyond my control

Answer

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

$.get('/foo', function(data) {
    data.phone = data.phone || "";
    $('#output').html(_d(data));
});

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 : ''});
    $('#output').html(_d(data));
});
Comments