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.
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"
Actually, you can use arguments
inside of your template:
<% if(!_.isUndefined(arguments[0].foo)) { %>
...
<% } %>
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.
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