Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe JavaScript Templates

I am looking to allow users to create templates to display their data, and these templates are to be rendered using JavaScript. I was wondering if it was possible to safely do this? I just need simple things like loops and if-else statements and of course accessing and printing values of variables in a given object.

Are there any template libraries that allow this, or easy methods for accomplishing this task?

like image 985
Stanislav Avatar asked Jul 07 '10 11:07

Stanislav


People also ask

Is there a JavaScript template?

Template7. Template7 is the first ever mobile-first templating engine for JavaScript which is build on Handlebars. It is easy and convenient for developers to use this templating system when it comes to building mobile apps and websites.

Which is better EJS or handlebars?

EJS is way faster than Jade and handlebars. EJS has a really smart error handling mechanism built right into it. It points out to you, the line numbers on which an error has occurred so that you don't end up looking through the whole template file wasting your time in searching for bugs.

Which is better Pug or EJS?

According to the StackShare community, Pug has a broader approval, being mentioned in 230 company stacks & 608 developers stacks; compared to EJS, which is listed in 9 company stacks and 13 developer stacks.


1 Answers

The following are considering possibly Node.js server-safe options (no arbitrary code execution / infinite loops). Browser safe (XSS) is hard / impossible.

Mustache appears to be explicitly designed to be safe for user consumption and prevent infinite loops to avoid server DoS: https://github.com/janl/mustache.js/

You can also look for JavaScript Liquid ports: Liquid templating for Node.js such as https://github.com/liquid-lang/liquid-node since Liquid is the default GitHub pages choice, so it should be safe to run on the server.

Options which are known not to be safe:

  • https://mozilla.github.io/nunjucks/templating.html "nunjucks does not sandbox execution so it is not safe to run user-defined templates or inject user-defined content into template definitions."