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

Add custom function constructor option #711

Open
wants to merge 2 commits into
base: main
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ You should never give end-users unfettered access to the EJS render method, If y
previously resolved path. Should return an object `{ filename, template }`,
you may return only one of the properties, where `filename` is the final parsed path and `template`
is the included content.
- `functionClass` Custom [function constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) replacement for a scenario where you would want to add hooks or provide a different execution backend.

This project uses [JSDoc](http://usejsdoc.org/). For the full public API
documentation, clone the repository and run `jake doc`. This will run JSDoc
Expand Down
5 changes: 4 additions & 1 deletion lib/ejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,7 @@ function Template(text, opts) {
options.async = opts.async;
options.destructuredLocals = opts.destructuredLocals;
options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
options.functionClass = typeof opts.functionClass === 'function' ? opts.functionClass : undefined;

if (options.strict) {
options._with = false;
Expand Down Expand Up @@ -652,7 +653,9 @@ Template.prototype = {
}

try {
if (opts.async) {
if (opts.functionClass !== undefined) {
ctor = opts.functionClass;
} else if (opts.async) {
// Have to use generated function for this, since in envs without support,
// it breaks in parsing
try {
Expand Down
9 changes: 9 additions & 0 deletions test/ejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,15 @@ suite('ejs.compile(str, options)', function () {
assert.ok(func.name === 'anonymous');
return done();
});

test('allow custom function ctor', function () {
var fn = ejs.compile('', {
functionClass: function(){
return function(){ return 'potato'; }
}
});
assert.equal(fn(), 'potato');
});
});

suite('client mode', function () {
Expand Down