Search code examples
javascripttemplate-enginedot.js

Is there a JavaScript HTML template that supports both null-coalescing ("undefined" safe) and protects from XSS?


I was looking for a JavaScript template engine, and chose DoT.js (mostly because it's very fast) but had the following issues

  • Null safe/Undefined safe/null-coalescing, Just like in Freemarker / VTL, I want to be able to pass foo.bar.foobar and not worry about checking foo, foo.bar and foo.bar.foobar that they are defined
    e.g. avoid things like

    {{ var val='';try{ var=foo.bar.foobar }catch(){} }}{{= val}}
    

    which I feel bad about, or

    {{= typeof foo !== 'undefined'?typeof foo.bar!=='undefined'?typeof foo.bar.foobar!=='undefined'?foo.bar.foobar:'foo.bar.foobar is undefined':'foo.bar is undefined':'foo is undefined'}}
    

    which I'm not sure if I feel better or worse about

  • I want to have good XSS protection, and as fast DoT.js are by not using DOM, even with the {{! }} operator, I'm not feeling comfortable that all XSS in the world will be handled by find and replace (e.g. what if the author missed something)

    Documentation although it's very fast, it's not that popular (yet), but the sources are so small you can figure out most things by just reading them, but having a good community is a great benefit

Which JavaScript template library answers these two requirements, and is still considered fast?


Solution

  • https://github.com/mikesamuel/jquery-jquery-tmpl-proposal benchmarks well against other template systems and has contextual autoescaping to prevent XSS.

    You can see from the conformance suite that it coalesces undefined.