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
The
||operator is useful for this sort of thing:But since you’re already using Underscore, you can use the
_.defaultsfunction. This approach is particularly useful for providing defaults for multiple fields: