如何将视图渲染为字符串?

时间:2013-10-11 19:16:48

标签: javascript views rendering sails.js

我想在sailsjs控制器/动作中呈现特定视图,该视图应作为电子邮件发送。

我有以下示例操作:

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
  });
}

如何使用sailsjs提供的工具渲染视图模板,以便我不需要对电子邮件文本进行硬编码或使用其他库?

提前致谢!

2 个答案:

答案 0 :(得分:3)

您的res对象中的res.render()仍然是accessible

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
  });
}

答案 1 :(得分:0)

为了改善crzrcn的答案,确保

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
  });
}