Permalink
Browse files

Added HTML escaping to the MicroTemplatingEngine, and tests.

  • Loading branch information...
1 parent 77d23ab commit e26fc8a8ba8cbd0e830a47914f938edc01697745 @thatismatt committed Jul 7, 2010
Showing with 23 additions and 5 deletions.
  1. +18 −5 lib/josi/templating.js
  2. +5 −0 tests/templating.js
View
@@ -51,12 +51,14 @@ var TemplatingEngine = Class.extend({
// single quote fix by Neil Donewar - #comment-321850
this.MicroTemplatingEngine = TemplatingEngine.extend({
compile: function(str) {
- return new Function("obj",
- "var __=[];" +
+ var unscopedTemplate = new Function("obj", "helpers",
+ "var __ = { stack: [], helpers: helpers };" +
+ // 'namespace' the view data if the user provided a namespace
(this.namespace ? 'obj.' + this.namespace + ' = obj;' : '') +
+
// Introduce the data as local variables using with(){}
- "with(obj){__.push('" +
+ "with(obj){__.stack.push('" +
// Convert the template into pure JavaScript
str
@@ -65,13 +67,24 @@ this.MicroTemplatingEngine = TemplatingEngine.extend({
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<%=(.+?)%>/g, "',$1,'")
+ .replace(/<%:(.+?)%>/g, "',__.helpers.escapeHTML($1),'")
.split("<%").join("');")
- .split("%>").join("__.push('") +
- "');}return __.join('');"
+ .split("%>").join("__.stack.push('") +
+ "');}return __.stack.join('');"
);
+ return function(obj) {
+ return unscopedTemplate(obj, { escapeHTML: escapeHTML });
+ };
}
});
+var escapeHTML = function (str) {
+ return str
+ .replace(/&/g,'&amp;')
+ .replace(/</g,'&lt;')
+ .replace(/>/g,'&gt;');
+};
+
// Adapted from jQuery Templating Plugin
// Copyright 2010, John Resig
// Dual licensed under the MIT or GPL Version 2 licenses.
View
@@ -52,5 +52,10 @@ this.tests = {
var template = compileTemplate('<% var doubleIt = function(it) { return it + it; }; %><%= doubleIt(c) %>');
var rendered = template({ c: 'd' });
assert.equal(rendered, 'dd');
+ },
+ 'MicroTemplatingEngine escape HTML': function() {
+ var template = compileTemplate('a <%: d %> b <%: e %> c');
+ var rendered = template({ d: '<div>', e: 'this & that' });
+ assert.equal(rendered, 'a &lt;div&gt; b this &amp; that c');
}
};

0 comments on commit e26fc8a

Please sign in to comment.