Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Closes #17 Allowing users to specify the this object used in a Jaml.T…

…emplate w/ test
  • Loading branch information...
commit 15ea81c738882298ef2787ff912da302b2a9cb23 1 parent 13d8d25
@erikvold erikvold authored
Showing with 33 additions and 8 deletions.
  1. +25 −1 specs/template_spec.js
  2. +4 −4 src/Jaml.js
  3. +4 −3 src/Template.js
View
26 specs/template_spec.js
@@ -117,7 +117,31 @@ describe("Jaml.Template", function() {
" <li>yellow</li>\n" +
" <li>purple</li>\n" +
"</ul>\n");
- });
+ });
+ it("renders the template for each item in the array, using thisObj", function(){
+ expect(new Jaml.Template(function(widget, i){
+ ul({id: i, data: this.data},
+ li(widget.primaryColor),
+ li(widget.secondaryColor)
+ )
+ }).render({data: "test"}, [
+ {primaryColor: "red", secondaryColor: "green"},
+ {primaryColor: "orange", secondaryColor: "blue"},
+ {primaryColor: "yellow", secondaryColor: "purple"}
+ ])).
+ toEqual("<ul data=\"test\" id=\"0\">\n" +
+ " <li>red</li>\n" +
+ " <li>green</li>\n" +
+ "</ul>\n" +
+ "<ul data=\"test\" id=\"1\">\n" +
+ " <li>orange</li>\n" +
+ " <li>blue</li>\n" +
+ "</ul>\n" +
+ "<ul data=\"test\" id=\"2\">\n" +
+ " <li>yellow</li>\n" +
+ " <li>purple</li>\n" +
+ "</ul>\n");
+ });
});
View
8 src/Jaml.js
@@ -21,13 +21,13 @@ Jaml = function() {
/**
* Renders the given template name with an optional data object
* @param {String} name The name of the template to render
+ * @param {Object} thisObj Optional data object
* @param {Object} data Optional data object
*/
- render: function(name, data) {
+ render: function(name, thisObj, data) {
var template = this.templates[name],
renderer = new Jaml.Template(template);
-
- return renderer.render(data);
- }
+ return renderer.render.apply(renderer, Array.prototype.slice.call(arguments, 1));
+ }
};
}();
View
7 src/Template.js
@@ -24,11 +24,12 @@ Jaml.Template = function(tpl) {
Jaml.Template.prototype = {
/**
* Renders this template given the supplied data
+ * @param {Object} thisObj Optional data object
* @param {Object} data Optional data object
* @return {String} The rendered HTML string
*/
- render: function(data) {
- data = data || {};
+ render: function(thisObj, data) {
+ data = data || (thisObj = thisObj || {});
//the 'data' argument can come in two flavours - array or non-array. Normalise it
//here so that it always looks like an array.
@@ -38,7 +39,7 @@ Jaml.Template.prototype = {
with(this) {
for (var i=0; i < data.length; i++) {
- eval("(" + this.tpl.toString() + ")(data[i], i)");
+ eval("(" + this.tpl.toString() + ").call(thisObj, data[i], i)");
};
}
Please sign in to comment.
Something went wrong with that request. Please try again.