Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring undefined data / vars in an underscore template

Still learning backbone so bear with me;

I'm trying to add a new model with blank fields to a view, but the template I've created has a whole bunch of

<input value="<%= some_value %>" type="whatever" />

Works perfectly fine when fetching data, it populates it and all goes well. The trouble arises when I want to create a new (blank) rendered view, it gives me

Uncaught ReferenceError: some_value is not defined

I can set defaults (I do already for a few that have default values in the db) but that means typing out over 40 of them with blanks; is there a better way of handling this?

I'm fiddling around with the underscore template itself, trying something like <%= if(some_value != undefined){ some_value } %> but that also seems a bit cumbersome.

like image 571
Shaz Amjad Avatar asked Mar 07 '13 23:03

Shaz Amjad


3 Answers

Pass the template data inside a wrapper object. Missing property access won't throw an error:

So, instead of:

var template = _.template('<%= foo %><%= bar %>');
var model = {foo:'foo'};
var result = template(model); //-> Error

Try:

var template = _.template('<%= model.foo %><%= model.bar %>');
var model = {foo:'foo'};
var result = template({model:model}); //-> "foo"
like image 133
jevakallio Avatar answered Oct 28 '22 20:10

jevakallio


Actually, you can use arguments inside of your template:

<% if(!_.isUndefined(arguments[0].foo)) { %>
       ...
<% } %>
like image 20
Dmitriy Avatar answered Oct 28 '22 19:10

Dmitriy


No,

There is no actual fix for this due to the way underscore templates are implemented.

See this discussion about it:

I'm afraid that this is simply the way that with(){} works in JS. If the variable isn't declared, it's a ReferenceError. There's nothing we can do about it, while preserving the rest of template behavior.

The only way you can accomplish what you're looking for is to either wrap the object with another object like the other answer suggested, or setting up defaults.

like image 25
Benjamin Gruenbaum Avatar answered Oct 28 '22 20:10

Benjamin Gruenbaum