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)
The reason you are experiancing this problem is that ejs cannot access the filesystem on client-side (javascript). So what is happening is this:
reports.ejs.include tag, it looks for that file.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With