2

[Note: This question is very similar, but not quite the same.]

I'm trying to do if statements with underscore templates. I have tried:

<% if (_id) { %><%=_id %><% } %>

and

<% if (_id) { _id } %>

and

<% if (_id) { <%= _id %> } %>

and a bunch of other combinations, but I always get the error

ReferenceError: _id is not defined

Any suggestions?

Community
  • 1
  • 1
Randomblue
  • 112,777
  • 145
  • 353
  • 547

2 Answers2

6

I have no idea what is your code, but _id is obviously an identifier. The problem, though, that you do not have _id defined.

As for suggestion, I'd probably suggest that you define it or use the one that is defined. It's hard to give you a better suggestion with zero context.

EDIT: you probably want if(typeof _id != 'undefined') instead.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
  • Here is the context. I render the template by passing an object wit properties. It turns out that sometimes `_id` is not one of the properties of that object. In that case, I just want to show nothing, but not error out. – Randomblue Dec 23 '11 at 23:08
  • Because if you reference undefined variable you get the not defined error with some javascript engines. – Michael Krelin - hacker Dec 23 '11 at 23:29
  • Aha. Could you link to further information regarding this. Because I constantly use the pattern `if(variable) { ... }` where `variable` could be `undefined`? – Randomblue Dec 24 '11 at 00:29
  • Here? http://stackoverflow.com/questions/138669/how-can-i-determine-if-a-javascript-variable-is-defined-in-a-page ? :) – Michael Krelin - hacker Dec 24 '11 at 00:44
  • You probably refer to object properties (`if(a.b)`) or function parameters. I think it works better in these cases. – Michael Krelin - hacker Dec 24 '11 at 00:46
0

A bit old, but this is how I solved a similar problem:

inside your model:

var Model = Backbone.Model.extend({

    defaults: {
        field1: null
    }

});

then in your template you can do:

<% if (field1) { %>
    ...
<% } else { %>
    ...
<% } %>
David Fregoli
  • 3,377
  • 1
  • 19
  • 40