Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 973
wiradikusuma Avatar asked Sep 09 '11 17:09

wiradikusuma


2 Answers

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));
});
like image 138
namuol Avatar answered Sep 27 '22 20:09

namuol


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.

like image 21
Roberto Alarcon Avatar answered Sep 27 '22 20:09

Roberto Alarcon