Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding in a way to not explicitly set context #303

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions doT.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,23 @@
+ doT.encodeHTMLSource.toString() + "(" + (c.doNotSkipEncoded || '') + "));"
+ str;
}

try {
if (c.varname.length === 0) {
var escapedFunctionBody = str
.replace(/\\'/g, "\\\\'")
.replace(/\\"/g, '\\\\"')
.replace(/(?!\\)'/g, "\\'")
.replace(/(?!\\)"/g, '\\"')
.replace(/\r/g, "\\r")
.replace(/\n/g, "\\n")
.replace(/\t/g, "\\t");

return new Function('it', (function (str) {
return 'return (new Function("{" + ' + "Object.keys(it).join(', ')" + ' + "}", "' + str + '"))(it)';
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"{" + ' + "Object.keys(it).join(', ')" + ' + "}"

Here we're getting all the keys in the object and exploding them so that we end up with new Function({foo, bar, baz}, "escapedFunctionBody"), which is what allows us to use the template in a non-context way. Object.keys is called when the outer function is called, as part of the process of building the inner function because it's not technically wrapped in "'s.

str is called when the inner function is executed because it is wrapped in "'s

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return (new Function("{" + ' + "Object.keys(it).join(', ')" + ' + "}", "' + str + '"))(it)

Since we want to perform the explosion at runtime, our outside function returns a self-calling function so that the user doesn't have to do something like doT.template(template)(data)(); This way when they do doT.template(template)(data) the inner function created and called at the same time

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Essentially this created a function that created a new function with the definition of automatically spreading out the passed in arguments so that you can have context-less templates. I'm aware that this is a feature in v2, but I thought it might be useful to add to v1, especially since v2 is in beta

@Garethp, having this implementation would cause doT v1 to fail on older browsers which are not es5 compliant

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@elcharitas True, but I think that it should still be backwards compatible with older v1 versions. All of the ES6 syntax exists inside the function that gets built at run-time only if you use the no-context option. Anyone should be able to upgrade to this change without affecting older browsers, it just means that the new feature wouldn't work on older browsers.

Is having a feature that's only available to browsers in the last 5-ish years a problem if it doesn't stop the package from working on older browsers the way it did previously?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wish i had a say on this as you've fully convinced me.

I was of the opinion that new features should just be implemented in v2 but taking a look at v2 again, i see a lot of breakage :(

Also, i think it's noteworthy that v1 hasn't been updated in a while. Hopefully this merge would be accepted as I'd love to see that happen

})(escapedFunctionBody));
}

return new Function(c.varname, str);
} catch (e) {
/* istanbul ignore else */
Expand Down
157 changes: 157 additions & 0 deletions test/noContext.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
'use strict';

var test = require('./util').testWithoutContext;
var assert = require("assert")
var doT = require("..");

var settings = {
evaluate: /\{\{([\s\S]+?(\}?)+)\}\}/g,
interpolate: /\{\{=([\s\S]+?)\}\}/g,
encode: /\{\{!([\s\S]+?)\}\}/g,
use: /\{\{#([\s\S]+?)\}\}/g,
useParams: /(^|[^\w$])def(?:\.|\[[\'\"])([\w$\.]+)(?:[\'\"]\])?\s*\:\s*([\w$\.]+|\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})/g,
define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
defineParams:/^\s*([\w$]+):([\s\S]+)/,
conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
varname: "",
strip: true,
append: true,
selfcontained: false,
doNotSkipEncoded: false
};

describe('noContext', function(){
describe('evaluate JavaScript', function() {
it('should print numbers next to each other', function() {
test([
'{{ one = 1; two = 2; }}{{= one }}{{= two }}',
], {}, '12');
});
});

describe('interpolate 2 numbers', function() {
it('should print numbers next to each other', function() {
test([
'{{=one}}{{=two}}',
'{{= one}}{{= two}}',
'{{= one }}{{= two }}'
], {one:1, two: 2}, '12');
});
});

describe('encoding with doNotSkipEncoded=false', function() {
it('should not replace &', function() {
global._encodeHTML = undefined;
doT.templateSettings.doNotSkipEncoded = false;
var fn = doT.template('<div>{{!foo}}</div>', settings);
assert.equal(fn({foo:"&amp;"}), "<div>&amp;</div>");
});
});

describe('encoding with doNotSkipEncoded=true', function() {
it('should replace &', function() {
global._encodeHTML = undefined;
settings.doNotSkipEncoded = true;
assert.equal(doT.template('<div>{{!foo}}</div>', settings)({foo:"&amp;"}), "<div>&#38;amp;</div>");
assert.equal(doT.template('{{!a}}', settings)({a:"& < > / ' \""}), "&#38; &#60; &#62; &#47; &#39; &#34;");
assert.equal(doT.template('{{!"& < > / \' \\""}}')(), "&#38; &#60; &#62; &#47; &#39; &#34;");
});
});

describe('invalid JS in templates', function() {
it('should throw exception', function() {
assert.throws(function() {
var fn = doT.template('<div>{{= foo + }}</div>', settings)();
});
});
});

describe('conditionals', function() {
describe('without else', function() {
var templates = [
'{{?one < 2}}{{=one}}{{?}}{{=two}}',
'{{? one < 2 }}{{= one }}{{?}}{{= two }}'
];

it('should evaluate condition and include template if valid', function() {
test(templates, {one: 1, two: 2}, '12')
});

it('should evaluate condition and do NOT include template if invalid', function() {
test(templates, {one: 3, two: 2}, '2')
});
});


describe('with else', function() {
var templates = [
'{{?one < 2}}{{=one}}{{??}}{{=two}}{{?}}',
'{{? one < 2 }}{{= one }}{{??}}{{= two }}{{?}}'
];

it('should evaluate condition and include "if" template if valid', function() {
test(templates, {one: 1, two: 2}, '1')
});

it('should evaluate condition and include "else" template if invalid', function() {
test(templates, {one: 3, two: 2}, '2')
});
});

describe('with else if', function() {
var templates = [
'{{?one < 2}}{{=one}}{{??two < 3}}{{=two}}{{??}}{{=three}}{{?}}',
'{{? one < 2 }}{{= one }}{{?? two < 3 }}{{= two }}{{??}}{{= three }}{{?}}'
];

it('should evaluate condition and include "if" template if valid', function() {
test(templates, {one: 1, two: 2, three: 3}, '1')
});

it('should evaluate condition and include "else if" template if second condition valid', function() {
test(templates, {one: 10, two: 2, three: 3}, '2')
});

it('should evaluate condition and include "else" template if invalid', function() {
test(templates, {one: 10, two: 20, three: 3}, '3')
});
});
});

describe('iteration', function() {
describe('without index', function() {
it('should repeat string N times', function() {
test([
'{{~arr:x}}*{{~}}',
'{{~ arr:x }}*{{~}}',
'{{~ arr: x }}*{{~}}',
'{{~ arr :x }}*{{~}}'
], {arr: Array(3)}, '***');
});

it('should concatenate items', function() {
test(['{{~arr:x}}{{=x}}{{~}}'], {arr: [1,2,3]}, '123');
});
});

describe('with index', function() {
it('should repeat string N times', function() {
test([
'{{~arr:x:i}}*{{~}}',
'{{~ arr : x : i }}*{{~}}'
], {arr: Array(3)}, '***');
});

it('should concatenate indices', function() {
test(['{{~arr:x:i}}{{=i}}{{~}}'], {arr: Array(3)}, '012');
});

it('should concatenate indices and items', function() {
test([
'{{~arr:x:i}}{{?i}}, {{?}}{{=i}}:{{=x}}{{~}}'
], {arr: [10,20,30]}, '0:10, 1:20, 2:30');
});
});
});
})
24 changes: 24 additions & 0 deletions test/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,27 @@ exports.test = function (templates, data, result) {
assert.strictEqual(fn(data), result);
});
};

exports.testWithoutContext = function (templates, data, result) {
var settings = {
evaluate: /\{\{([\s\S]+?(\}?)+)\}\}/g,
interpolate: /\{\{=([\s\S]+?)\}\}/g,
encode: /\{\{!([\s\S]+?)\}\}/g,
use: /\{\{#([\s\S]+?)\}\}/g,
useParams: /(^|[^\w$])def(?:\.|\[[\'\"])([\w$\.]+)(?:[\'\"]\])?\s*\:\s*([\w$\.]+|\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})/g,
define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
defineParams:/^\s*([\w$]+):([\s\S]+)/,
conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
varname: "",
strip: true,
append: true,
selfcontained: false,
doNotSkipEncoded: false
};

templates.forEach(function (tmpl) {
var fn = doT.template(tmpl, settings);
assert.strictEqual(fn(data), result);
});
};