avoid undefined / type errors for complex / deep / nested object trees the brute force way #24

wants to merge 1 commit into from

4 participants


I'm not sure it's the best way, but I added a new "safe" interpolation option that will eval to '' if anything "bad" happens. (e.g. one of the objects is null or undefined, or simply you got an exception)
This is common in template languages (e.g. in Freemarker and VTL the ${! prefix )

I used {{~ }} for this notation, (e.g. if {{~a.b.c}} is called and b is undefined, it will return '' gracefully)

Since it's a new interpolation type, I think that if not used, it's only a very small performance issue (of course that the try catch is a very slow and bad practice, but doing {{= typeof a.b == 'undefined' ? '' : a.b}} is worse in my opinion (in terms of programmer productivity

I will not be offended and will still love DoT.js if you reject this pull request, it's one of my first ones

any comments are welcome, be gentle please... ;)

@eranation eranation For lazy people (like me) ability to "try catch" wrap an interpolatio…
…n to avoid "undefined" nested object tree issues, just nice to have there in case you really want to program by exception and know what you are doing
@eranation eranation commented on the diff Mar 27, 2012
@@ -67,6 +68,9 @@
.replace(c.interpolate, function(match, code) {
return cstart + code.replace(/\\'/g, "'").replace(/\\\\/g,"\\").replace(/[\r\t\n]/g, ' ') + cend;
+ .replace(c.interpolateSafe, function(match, code) {
+ return "';" + "var val = ''; try{val = " + code.replace(/\\'/g, "'").replace(/\\\\/g,"\\").replace(/[\r\t\n]/g, ' ') + ";}catch(e){}; out+= val + '";
+ })

oops, I'll indent it to the left... saw it only after the pull request...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

This type of situation can alleviated with either a conditional, or a NEW context delimiter (which I am for), or a combination of the 2. Overall I'm not really for something like this. Because you can wrap the whole template in a try catch like so.

var tpl = doT.template();
try { tpl(data) } catch (e) {}

The beauty of doT is that it precompiles your template into a function that JUST does string concatenation. Errors need to be handled, but I don't think they should be handled in the template itself.


I am doing a try-catch statement but there is nothing in the error. The only way to get any meaningful output is to take the try-catch out and force it to fail while watching stdout. What am I missing? Thanks!


It's easier to notice problems if expressions that can't be evaluated return the original markup, rather than empty string. Ideally there would be an option to do that, which you could switch off in production if desired.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment