Permalink
Browse files

Handle null and undefined a little better. Impleted ifdef and ifndef …

…for simple switching on undefined.
  • Loading branch information...
1 parent 48b8e06 commit fad14d9021c7bcc0d28a3b32cd5a53fe3c603978 @rdworth committed Apr 5, 2010
Showing with 40 additions and 6 deletions.
  1. +30 −4 demo.html
  2. +10 −2 jquery.tmpl.js
View
@@ -18,9 +18,19 @@
]
};
- var arrayOfDataObjects = [ dataObject, dataObject, dataObject ];
+ var arrayOfDataObjects = [
+ $.extend({}, dataObject),
+ $.extend({}, dataObject),
+ $.extend({}, dataObject)
+ ];
+
+ arrayOfDataObjects[0].age = 25;
+ arrayOfDataObjects[1].foo = { bar: undefined };
+ arrayOfDataObjects[1].age = null;
+ arrayOfDataObjects[1].foo = { bar: null };
+ arrayOfDataObjects[2].foo = { bar: 'baz' };
- var tmpl = '<li>${$i}) <a href="${url}">${name}</a> (${cityJoin})</li>';
+ var tmpl = '<li>${$i}) <a href="${url}">${name}</a> (age: ${age}) (${cityJoin})</li>';
$("#sometmpl")
.render( dataObject ) // Returns a LI with all the data filled in
@@ -43,11 +53,27 @@
</script>
<script id="sometmpl" type="text/html">
- <li>${$i}) <a href="${url}">${name}</a> Age: ${age} (${cityJoin})</li>
+ <li>${$i}) <a href="${url}">${name}</a>
+ {{ifdef age}}Age:
+ {{if age != null}}${age}
+ {{else}}(null)
+ {{/if}}
+ {{/ifdef}}
+ {{ifndef age}}(no age defined){{/ifndef}}
+ (${cityJoin})</li>
</script>
<script id="sometmpl2" type="text/html">
- <li>${$i}) <a href="${url}">${name}</a> Cities: {{each(i,city) cities}}${city}{{/each}}</li>
+ ${foo}
+ <li>
+ ${$i}) <a href="${url}">${name}</a>
+ Age:
+ {{ifdef age}}${age}{{else}}--{{/ifdef}}
+ Cities: {{each(i,city) cities}}${city}{{/each}}
+ {{ifdef foo.bar}}foo.bar is defined{{/ifdef}}
+ {{ifndef foo.bar}}foo.bar not defined{{/ifndef}}
+ {{= "['" + foo.bar + "']" }}
+ </li>
</script>
<ul></ul>
View
@@ -77,7 +77,15 @@
suffix: "}});"
},
if: {
- prefix: "if($1){",
+ prefix: "try{if($1){",
+ suffix: "}}catch(e){}"
+ },
+ ifdef: {
+ prefix: "try{if(typeof($1)!=='undefined'){",
+ suffix: "}}catch(e){}"
+ },
+ ifndef: {
+ prefix: "try{if(typeof($1)==='undefined'){throw 'undefined';}}catch(e){",
suffix: "}"
},
else: {
@@ -116,7 +124,7 @@
throw "Template not found: " + type;
}
- var def = tmpl._default;
+ var def = tmpl._default | [];
return "');" + tmpl[slash ? "suffix" : "prefix"]
.split("$1").join(args || def[0])

2 comments on commit fad14d9

@borgar
borgar commented on fad14d9 Apr 5, 2010

I may be wrong (have not run the code) but doesn't ifdef swallow up every error that occurs within the block?

@rdworth
Owner
rdworth commented on fad14d9 Apr 6, 2010

You're right. Fixed in SHA: 267d7fc . Thanks.

Please sign in to comment.