I am having a hard time determining if data passed into the jquery template exists and is false without getting errors. This is what I am using to test
<html>
<head>
<title>jQuery Templates {{if}} logic</title>
</head>
<body>
<p id="results"></p>
<p>How do you test if the Value exists and is false?</p>
<script id="testTemplate" type="text/html">
Test ${Test}:
{{if Value}}
Value exists and is true
{{else}}
Value doesn't exist or is false
{{/if}}
<br/>
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.tmpl.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#testTemplate").tmpl({Test:1}).appendTo("#results");
$("#testTemplate").tmpl({Test:2, Value:true}).appendTo("#results");
$("#testTemplate").tmpl({Test:3, Value:false}).appendTo("#results");
});
</script>
</body></html>
Does anyone know how to do it?
You can use another else
statement in there using a === false
check, like this:
{{if Value}}
Value exists and is true
{{else typeof(Value) != "undefined" && Value === false}}
Value exists and is false
{{else}}
Value doesn't exist or isn't explicitly false
{{/if}}
You can test it out here. The typeof
check is because you'll get a Value is not defined
error with only Value === false
. You would add other checks as well, for example {{else typeof(Value) == "undefined"}}
would be true if the value wasn't specified.
You could write a function to check for you:
$(document).ready(function() {
function isExplicitlyFalse(f) { return f === false; }
$("#testTemplate").tmpl({Test:1, isExplicitlyFalse: isExplicitlyFalse}).appendTo("#results");
$("#testTemplate").tmpl({Test:2, Value:true, isExplicitlyFalse: isExplicitlyFalse}).appendTo("#results");
$("#testTemplate").tmpl({Test:3, Value:false, isExplicitlyFalse: isExplicitlyFalse}).appendTo("#results");
});
then in your template:
{{if item.isExplicitlyFalse(Value)}}
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