Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax with include in ejs

When i try to add include in my ejs file its working fine. HTML report.ejs

<tbody>                  
    <%- include('include/playersTable'); %>
</tbody>

Javascript

$.get('/reports.ejs', function (template) {
    // Compile the EJS template.
    reportTemplate = ejs.compile(template);
});

But when i call it with ajax it says include use relative path requires the 'filename' option.

And when i try it with client site

Javascript

$.get('/reports.ejs', function (template) {
    // Compile the EJS template.
    reportTemplate = ejs.compile(template, {client: true});
});

it says

include is not a function at eval (eval at compile (ejs.js:525), :103:17)

like image 207
Navneet Garg Avatar asked Jul 10 '26 11:07

Navneet Garg


1 Answers

The reason you are experiancing this problem is that ejs cannot access the filesystem on client-side (javascript). So what is happening is this:

  1. ajax gets the reports.ejs.
  2. ejs starts compiling.
  3. when ejs gets to an include tag, it looks for that file.
  4. since it cannot access the filesystem, it cannot find the file.
  5. ejs sends an error.

On the ejs website it says:

Most of EJS will work as expected; however, there are a few things to note:

Since you do not have access to the filesystem, ejs.renderFile won't work. For the same reason, includes do not work unless you use an include callback. Here is an example:

let str = "Hello <%= include('file', {person: 'John'}); %>",
      fn = ejs.compile(str, {client: true});

fn(data, null, function(path, d){ // include callback
  // path -> 'file'
  // d -> {person: 'John'}
  // Put your code here
  // Return the contents of file as a string
}); // returns rendered string

Another workaround I recommend would be to define an ajax route, like so:


app.get('/ajax/:filename', (req, res) => {
  res.render(req.params['filename'], req.query);
  // This allows you to pass data in ajax like: `$.get("/ajax/reports?username=jhon&hello=world")`
});

This does the rendering server-side, which can access the filesystem.

like image 93
coderkearns Avatar answered Jul 13 '26 10:07

coderkearns