mde / ejs

Embedded JavaScript templates -- http://ejs.co
Apache License 2.0
7.71k stars 846 forks source link

Proposed alternative to `_with=false` #624

Open bjones1 opened 3 years ago

bjones1 commented 3 years ago

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.