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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
Because if you reference undefined variable you get the not defined error with some javascript engines.
Aha. Could you link to further information regarding this. Because I constantly use the pattern if(variable) { ... } where variable could be undefined?
You probably refer to object properties (if(a.b)) or function parameters. I think it works better in these cases.
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 { %>
    ...
<% } %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.