ejs icon indicating copy to clipboard operation
ejs copied to clipboard

Error (and solution?) when including from variable

Open JKershaw opened this issue 5 years ago • 2 comments

There are some situations where the <%- include(variable) %> will fail to find the correct file 9in my case, trying to include via variable name in a loop, within an already included file).

In the getIncludePath function, if options.views is not an array but a single string, it will fail with the "Could not find the include file" error.

Adding a condition to find valid views directories from a string, and not just an array, solves this issue. So it goes from

   // Then look in any views directories
    if (!includePath) {
      if (Array.isArray(views) && views.some(function (v) {
        filePath = exports.resolveInclude(path, v, true);
        return fs.existsSync(filePath);
      })) {
        includePath = filePath;
      } 
    }

to something along the lines of

    // Then look in any views directories
    if (!includePath) {
      if (Array.isArray(views) && views.some(function (v) {
        filePath = exports.resolveInclude(path, v, true);
        return fs.existsSync(filePath);
      })) {
        includePath = filePath;
      } else {
        filePath = exports.resolveInclude(path, views, true);
        if (fs.existsSync(filePath)) {
          includePath = filePath;
        }
      }
    }

and now works with the extra check.

I'm not sure if this is a bug as I'm not super familiar with the inner workings of ejs, but this has been an issue that's cropped up a few times.

JKershaw avatar Dec 17 '18 12:12 JKershaw

A simpler solution might be just a check to ensure that views is an array, something like views = [].concat(views). I'd happily merge a PR that adds that check.

mde avatar Dec 17 '18 16:12 mde

Good point. I've created a PR for this.

JKershaw avatar Dec 18 '18 12:12 JKershaw