This is undocumented, but EJS just compiles your template to a JS function that returns the rendered content. It adds a variable called __output
that contains the current output so far. See the EJS source here: https://github.com/mde/ejs/blob/820855ad75034e303be82c482c5eb8c6616da5c5/lib/ejs.js#L589
So, if you are fine with relying on these two undocumented behaviors (__output
and EJS compiling to a function), you can simply use return __output;
as a die();
.
This:
one
<% return __output; %>
two
Will only render one
.
To only rely on the first undocumented behavior, you can throw a special exception in the template that is then caught by the render function. You still need __output
though since there is otherwise no way to obtain the partially-generated output. Something like this:
class StopEJSError extends Error {};
const die = (output) => {
const err = new StopEJSError();
err._output = output;
throw err;
};
ejs.renderFile("template.ejs", {die}, (err, out) => {
if (err instanceof StopEJSError) {
res.send(err.output);
} else if (err) {
throw err;
} else res.send(out);
});