ejs
ejs copied to clipboard
Proposed alternative to `_with=false`
In my application, I'd like to run all JavaScript in strict mode, so I pass strict=true in the EJS options dict. This means that the with statement can't be used -- which I really miss; template variables are now locals.a instead of a. [1] Therefore, I wrote a small addition to EJS to wrap the replacement statements in a dynamically-generated function: I can run templates in strict mode and still refer to template variables as a. Would @mde be interested in a PR with this code? Here's the core of it, added to Template.function:
if (opts._with === false) {
prepended += ' Function.apply(null, ["__append", "escapeFn"].concat(Object.keys(' +
opts.localsName + ' || {}), [\n';
appended += '])).apply(null, [__append, escapeFn].concat(Object.values(' +
opts.localsName + ' || {})));\n';
this.source = JSON.stringify(this.source);
}
[1] Yes, I could pass something like localsName=v to the EJS options dict then refer to variables as v.a, but that's still a bit more awkward than a.