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:
$.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));
});
I liked @namuol solution, another thing that we could do is set the defaults hash at the model extends
var MyModel = Backbone.Model.extend({
defaults: {
"foo": "I",
"bar": "love",
"yeah": "sara"
}
});
Just another option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With