How to use the renderFile function from ejs

Find comprehensive JavaScript ejs.renderFile code examples handpicked from public code repositorys.

ejs.renderFile is a function that compiles an EJS template file and returns the resulting HTML markup as a string.

9
10
11
12
13
14
15
16
17
18
  return fs.readFileSync(path.normalize(path.join(__dirname, '..', filePath)));
};

module.exports = function handleErrors(document) {
  function renderErrorPage(data) {
    ejs.renderFile('error.ejs', data, (err, content) => {
      if (err) {
        // eslint-disable-next-line no-console
        console.error(`Failed to render error page. Error code "${data.errorDescription}".`);
        return;
fork icon73
star icon198
watch icon0

96
97
98
99
100
101
102
103
104
105
}

// eslint-disable-next-line no-underscore-dangle
__ = i18n.__(config.language);
_context.next = 14;
return ejs.renderFile(path.join(__dirname, 'templates/bangumi.ejs'), {
  quote: config[type].quote,
  show: config[type].show || 1,
  loading: config[type].loading,
  metaColor: config[type].metaColor ? "style=\"color:".concat(config[type].metaColor, "\"") : '',
fork icon15
star icon276
watch icon1

+ 5 other calls in file

How does ejs.renderFile work?

ejs.renderFile is a function that takes a file path and an optional set of data, reads the contents of the specified file, and then compiles and renders the file using the EJS template engine, optionally replacing any dynamic content in the template with the provided data. The resulting HTML or text is then returned as a string.

186
187
188
189
190
191
192
193
194
195

contentParse(content, options, done) {
    this.parser(content, options, done);
}
templateRender(data, done) {
    ejs.renderFile(this.template, data, {}, done);
}
loadFileXEJS(file, options, done) {
    xejsParser(file, options, this.xejsTokens, done);
}
fork icon14
star icon0
watch icon3

111
112
113
114
115
116
117
118
119
120
let files = globFiles(config.src_globs, { cwd: config.src });
console.log(` pages count: ${files.length}`);
files.map(name => {
        count++;
        let path = joinPath(config.src, name);
        processorConfig.ejs ? ejs.renderFile(path, ejsRenderVariables, { root: config.src }, callback)  
                : fs.readFile(path, 'utf8', callback);
        function callback(err, content) {
                if (--count <= 0) log.done();
                if (err) return console.error(`  error: render page ${path}`.red, '\n', err.stack);
fork icon1
star icon1
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const ejs = require("ejs");
const fs = require("fs");

const data = { title: "My Website", message: "Hello World!" };

ejs.renderFile("index.ejs", data, (err, html) => {
  if (err) {
    console.error(err);
  } else {
    fs.writeFile("index.html", html, (err) => {
      if (err) {
        console.error(err);
      } else {
        console.log("Successfully generated index.html!");
      }
    });
  }
});

In this example, we pass the name of the EJS template file (index.ejs) and some data ({ title: 'My Website', message: 'Hello World!' }) to the ejs.renderFile() function, which renders the template with the provided data. The resulting HTML is then written to a file named index.html using Node.js' fs.writeFile() function.

5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
    var balance_cf = 0;
  } else {
    var balance_cf = salary_data.leave_balance_cf - absentDaysInMonth;
  }
}
const html = await ejs.renderFile(
  "src/views/partials/salary_slip.ejs",
  {
    salary: SalaryStructureData ? SalaryStructureData : "no data found",
    user: UserData,
fork icon0
star icon2
watch icon1

+ 4 other calls in file

140
141
142
143
144
145
146
147
148
149
    return;
  }
});
res.status(200).json({ message: "Usuario creado con éxito" });
// Renderiza la plantilla con la variable del enlace
ejs.renderFile(__dirname + '/sign_up.ejs', { username, link }, (error, data) => {
  if (error) {
    console.log(error);
    res.send(error);
  } else {
fork icon0
star icon1
watch icon1

+ 6 other calls in file

31
32
33
34
35
36
37
38
39
40
const generateUuid = uuid.v1();


if(pagina1.length <= 10){
    
    ejs.renderFile(path.join(__dirname,'./','escalas.ejs'),
    {pagina1:pagina1,pagina2:pagina2,pagina3:pagina3,pagina4:pagina4,pagina5:pagina5,pagina6:pagina6,pagina7:pagina7,pagina8:pagina8,pagina9:pagina9,pagina10:pagina10,tipo:tipo},(err,results)=>{
  
        if(err){
          return res.status(500).json("error"+err)
fork icon0
star icon0
watch icon1

+ 49 other calls in file

29
30
31
32
33
34
35
36
37
38
});

socket.on('chat message', async function (message) {

    var aligner = "left";
    var renderedChat = await ejs.renderFile(path.join(__dirname + '/../' + 'views/' + 'chatbox.ejs'), { message: message, username: username, aligner: aligner });
    const html = renderedChat.toString();
    socket.broadcast.to(roomName).emit('chat message', renderedChat);
    aligner = "right";
    username = "You";
fork icon0
star icon0
watch icon1

+ 7 other calls in file

55
56
57
58
59
60
61
62
63
  return;
}


if (existsSync(viewPath)) {
  ejs.renderFile(viewPath, data ?? {}, (err, data) => {
    if (err) {
      console.error(err);
    }
fork icon0
star icon0
watch icon1

+ 3 other calls in file

20
21
22
23
24
25
26
27
28
29
30
const { AuthError } = require('./auth-controller');
const { ExtensionError } = require('./extension-controller');


const renderFile = (file, data) => {
    return new Promise((resolve, reject) => {
        ejs.renderFile(file, data, (err, result) => {
            if (err)
                reject(err);
            else
                resolve(result);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

448
449
450
451
452
453
454
455
456
457
//     res.setHeader('Content-Length', stat.size);
//     res.setHeader('Content-Type', 'application/pdf');
//     res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
//     file.pipe(res);
// })();
ejs.renderFile(path.join(__dirname, './views/', "view.ejs"), { id: `${data[0].id}`, _select: `${data[0]._select}`, reason_for_audio_only: `${data[0].reason_for_audio_only}`, chart_id: `${data[0].chart_id}`, insurance_id: `${data[0].insurance_id}`, dob: `${data[0].dob}`, consumer_name: `${data[0].consumer_name}`, icd_10: `${data[0].icd_10}`, medicare: `${data[0].medicare}`, name_of_supervising_physician: `${data[0].name_of_supervising_physician}`, co_pay_amount: `${data[0].co_pay_amount}`, paid_amount: `${data[0].paid_amount}`, id: `${data[0].id}`, time_in: `${data[0].time_in}`, time_out: `${data[0].time_out}`, am_or_pm: `${data[0].am_or_pm}`, county: `${data[0].county}`, insurance_carrier: `${data[0].insurance_carrier}`, assessment_done: `${data[0].assessment_done}`, dora: `${data[0].dora}`, in_treatment: `${data[0].in_treatment}`, referred: `${data[0].referred}`, clinician_services: `${data[0].clinician_services}`, sigt: `${data[0].signature}`, sigtp: `${data[0].signaturep}`, name_of_thera: `${data[0].name_of_thera}`, name_of_client: `${data[0].name_of_client}` }, (err, data1) => {
    if (err) {
        res.send(err);
    } else {
        let options = {
fork icon0
star icon0
watch icon1

+ 14 other calls in file

460
461
462
463
464
465
466
467
468
469
470
})


app.get("/generateReport/:id", (req, res) => {
    let id = req.params.id
    getPersonById({ id: id }, (x, data) => {
        ejs.renderFile(path.join(__dirname, './views/', "view.ejs"), { id: `${data[0].id}`, _select: `${data[0]._select}`, reason_for_audio_only: `${data[0].reason_for_audio_only}`, chart_id: `${data[0].chart_id}`, insurance_id: `${data[0].insurance_id}`, dob: `${data[0].dob}`, icd_10: `${data[0].icd_10}`, medicare: `${data[0].medicare}`, name_of_supervising_physician: `${data[0].name_of_supervising_physician}`, co_pay_amount: `${data[0].co_pay_amount}`, paid_amount: `${data[0].paid_amount}`, id: `${data[0].id}`, time_in: `${data[0].time_in}`, time_out: `${data[0].time_out}`, am_or_pm: `${data[0].am_or_pm}`, county: `${data[0].county}`, insurance_carrier: `${data[0].insurance_carrier}`, assessment_done: `${data[0].assessment_done}`, dora: `${data[0].dora}`, in_treatment: `${data[0].in_treatment}`, referred: `${data[0].referred}`, clinician_services: `${data[0].clinician_services}`, sigt: `${data[0].signature}`, sigtp: `${data[0].signaturep}`, name_of_thera: `${data[0].name_of_thera}` }, (err, data) => {
            if (err) {
                res.send(err);
            } else {
                let options = {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

478
479
480
481
482
483
484
485
486
487
}
/*renderEnvSettings.sessionId = await Secure.getSessionId(uuid,renderEnvSettings.requestIp,renderEnvSettings.cookies);
let returnCookies:Cookie[] = [];
if(renderEnvSettings.cookies['session']==undefined){returnCookies.push(new Cookie('session',renderEnvSettings.sessionId));}
let p:Promise<WebResponse>  = new Promise(function (resolve, reject) {
    ejs.renderFile(ejsRootFile, renderEnvSettings, {}, async function(err:string, result:string){	// renderFile( filename, data, options, callback
        if( err ){
            console.log('error rendering root ejs');
            console.log(err);
            resolve(new WebResponse(false, 'ERROR: Problem rendering ejs file',`UUID:${uuid} Problem rendering ejs file`,err,returnCookies));
fork icon0
star icon0
watch icon1

+ 19 other calls in file

261
262
263
264
265
266
267
268
269
270
  }
}
// if (FORGOT_PASSWORD_WITH.LINK.sms) {
//   let viewType = '/reset-password/';
//   let link = `http://localhost:${process.env.PORT}${viewType + token}`;
//   const msg = await ejs.renderFile(`${__basedir}/views/sms/ResetPassword/html.ejs`, { link: link });
//   let smsObj = {
//     to: user.mobileNo,
//     message: msg
//   };
fork icon0
star icon0
watch icon1

190
191
192
193
194
195
196
197
198
199
Async.map(files, (name, callback) => {
        let path = joinPath(config.src, name);
        if (isPugFile(name) && processorConfig.pug.enable)
                return render(null, pug.compileFile(path, getPugOptions(path))(ejsRenderVariables));
        if (processorConfig.ejs.enable)
                return ejs.renderFile(path, ejsRenderVariables, { root: config.src }, render);
        readFile(path, render);

        function render(err, content) {
                if (err) return callback({ path, err });
fork icon0
star icon0
watch icon2