Search code examples
javascriptbackbone.jsunderscore.js

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.


Solution

  • 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.