How to render a view to a string?

2019-01-29 03:40发布

I want to render a specific view in a sailsjs controller/action which should be sent out as email.

I have the following sample action:

function registerAction(req, res) {
   // handle user registration


  // email user
  sendEmail({
      to: newUser.email,
      subject: "Welcome",
      text: /* VIEW RENDER HERE */
  });

  // render view to the user
  return res.view({
     user: newUser
  });
}

How can I render a view-template with the tools sailsjs provides so that I don't need to hardcode an email text or use other libraries?

Thanks in advance!

2条回答
戒情不戒烟
2楼-- · 2019-01-29 04:22

To improve a little on crzrcn's answer, to ensure

function registerAction(req, res) {
   // handle user registration

  // don't include the .ejs of the end of your view, this assumes a file in path/to/view.ejs
  res.render('path/to/view', function (err, html) {
    // email user
    sendEmail({
        to: newUser.email,
        subject: "Welcome",
        html: html // rather than text in crzrcn's answer
    });
  }

  // render view to the user
  return res.view({
     user: newUser
  });
}
查看更多
Viruses.
3楼-- · 2019-01-29 04:25

Express' res.render() is still accessible in your res object.

function registerAction(req, res) {
   // handle user registration

  res.render('/path/to/view', function (err, html) {
    // email user
    sendEmail({
        to: newUser.email,
        subject: "Welcome",
        text: html
    });
  }

  // render view to the user
  return res.view({
     user: newUser
  });
}
查看更多
登录 后发表回答