jashkenas/underscore

_.template: some method for automatically escaping strings?

Closed this issue · 5 comments

Has there been any discussion regarding escaping HTML in template strings?

IMO it would be very nice to have the option to automatically escape <%='d strings.

I suggest leaving <%= as is and adding a tag which'd evaluate, escape, then print.

<%= 'AT&T' %> // AT&T
<%~ 'AT&T' %> // AT&amp;T

I'm happy to write a patch for this you agree, Jeremy, that it's a good idea.

Alright, so what if we don't make the wild and baseless assumption that HTML will be generated and parameterize the autoescape function? Then, for example, if someone is generating LaTeX, they can set _.templateAutoEscape = function(str) { str.replace(/([_&\\])/, "\\$1") } (or whatever the appropriate function would be).

dvv commented

In fact, better to fork kinda special _.templateHTML. You might want to look at my fork.

Yep, I'm afraid this is a duplicate ticket -- I'm of the general philosophy that escaping should be done closer to your data than in the templating language ... and that said, there are a multitude of other templating options out there for those who feel differently, including many that share syntax with _.template.

http://jsperf.com/dom-vs-innerhtml-based-templating/73