0

I want to print a userlist in a table using ejs into HTML template in Node js. So I am creating a API, my function is

const UsersReport = async (req, res) => {
  try {
    const users = await User.find().select(
      "name email mobile userType activeStatus photo accountType"
    );

    console.log("users", users);
    let pdf_path = path.normalize("public/user");
    if (!fs.existsSync(pdf_path)) {
      fs.mkdirSync(pdf_path);
    }
    const template = fs.readFileSync(
      path.resolve("templates/userList/index.html"),
      "utf8"
    );

    const content = ejs.render(template, users);
    let fullPdfPath = pdf_path + "/users.pdf";
    fs.writeFile(pdf_path + "/users.html", content, () => {
      let port = 5000;
      const url = `http://localhost:${port}/user/users.html`;
      const option = {
        format: "A4",
        path: fullPdfPath,
        printBackground: true,
      };
      const file = {
        url,
      };
      console.log("generating pdf");
      html_to_pdf.generatePdf(file, option).then((pdfbuf) => {
        console.log("pdf sent successfully");
        return response(res, StatusCodes.OK, true, "user/users.pdf", null);
      });
    });
  } catch (error) {
    return response(
      res,
      StatusCodes.INTERNAL_SERVER_ERROR,
      false,
      error,
      error.message
    );
  }
};

Here users return an array of object.

My HTML Template code is

<tr>
        <th>Name</th>
        <th>Contact</th>
      </tr>
      <tr>
        <% for(let i = 0; i <= users.length; i++ ){ %>
          <td><%= users[i].name %></td>
          <td><%= users[i].mobile %></td>
          <% } %>
      </tr>

But I didn't get the result this showing the following error

{ "status": false, "data": { "path": "" }, "message": "ejs:21\n 19| \r\n 20| \r\n >> 21| <% for(let i = 0; i <= users.length; i++ ){ %>\r\n 22| <%= users[i].name %>\r\n 23|

\r\n 24| \r\n\nusers is not defined" }

How can I solve this one?

0

1 Answer 1

1

If I'm not mistaken, users should be in brackets (see examples on main page):

const content = ejs.render(template, { users });

to use something in a template, it should be given as a property in an object. { users } is just shorthand for { users: users }.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.