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

StackOverflow https://stackoverflow.com/questions/9959842

Question

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?

Was it helpful?

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.

OTHER TIPS

mustache.js - Logic-less {{mustache}} templates with JavaScript.

1) If the key exists and has a value of null, undefined, or false, or is an empty list, the block will not be rendered.

2) All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: {{{name}}}. You can also use & to unescape a variable.

Reference: https://github.com/janl/mustache.js

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top