Rush Frisby
Rush Frisby

Reputation: 11454

jQuery tmpl {{if}} condition with false not working

I am using this in part of my template:

{{if !IsDefault}}
    <a href="#" onclick="makeDefault('${Id}');return false;">Make Default</a>
{{/if}}

Except when IsDefault is false it is not working. I even tried:

{{if IsDefault === false}}` and `{{if IsDefault == false}}

I have verified that the value actually is false in my json object that gets passed to the template.

I also tried this which works but is pretty ugly and I would prefer for it to just work how it should:

{{if IsDefault}}
{{else}}
    <a href="#" onclick="makeDefault('${Id}');return false;">Make Default</a>
{{/if}}

Also, if I change it to check for a true condition (doesn't make sense but just tried it for debugging purposes)...

{{if IsDefault}}

...it works fine. Looks like it just has problems with the false values. I am getting the json via an jQuery ajax call and using knockout mapping with jquery tmpl. I get no js errors.

Any ideas on why testing for false or !false is not working?

Upvotes: 2

Views: 4608

Answers (2)

Jaider
Jaider

Reputation: 14884

For a Jquery Template like this:

{{if !IsDefault}}
    html_code
{{/if}}

The code is interpreted as this:

if ((typeof(!IsDefault) !== 'undefined' && (!IsDefault) != null) && (typeof(!IsDefault) === 'function' ? (!IsDefault).call($item) : (!IsDefault))) 
{
    __.push(html_code);
}

and because of this typeof(!IsDefault), and the variable IsDefault doesn't exist, you will see Uncaught ReferenceError: IsDefault is not defined

I don't know how to solve this, but for the meantime, this works for me:

{{if IsDefault}}
{{else}}
    html_code
{{/if}}

Upvotes: 1

RP Niemeyer
RP Niemeyer

Reputation: 114792

Try using {{if !(IsDefault())}}

If you are using an observable that is not in an expression, then jQuery templates sees that it is a function and calls it as a function to get the observable's value. If it is in an expression, then this doesn't happen and you need to call your observable as a function (with no args) to get its value.

Upvotes: 4

Related Questions