【问题标题】:Meteor templates not recognized in server code服务器代码中无法识别 Meteor 模板
【发布时间】:2015-11-24 22:25:30
【问题描述】:

我正在 Meteor 中构建一个应用程序,并尝试从服务器端方法发送电子邮件。电子邮件的模板存在于我的 client/views 文件夹中。因此,当我尝试从服务器端代码发送电子邮件时,我收到错误“模板未定义”。这是我的代码:

/server/methods/sendemail.js

var html = Blaze.toHTMLWithData(Template.emailToCustomer, dataContext);
Meteor.call('sendEmail',
                 thisUser.emails[0].address,
                'mine@mine.org',
                'yours@gmail.com',
                 'email subject',
                  html
                );

我的电子邮件模板只是一个简单的 html 页面。请注意,如果它存在于 client/views/mytemplate.js 中,则此代码可以正常工作。但是,出于技术原因,我需要从服务器端代码发送电子邮件。

我尝试将 mytemplate.html 和 mytemplate.js 文件放在 app/both 和 app/server 文件夹中,但我仍然收到模板未定义错误。

有人知道会发生什么吗?

谢谢!

【问题讨论】:

    标签: javascript email templates meteor server


    【解决方案1】:

    您的模板是在客户端目录下定义的,因此它们在服务器上下文中不可用是正常的。

    遗憾的是,目前无法使用普通 Meteor API 访问 Blaze 模板,即使您将模板移动到客户端和服务器都可用的共享目录。

    您可以做的是使用meteorhacks:ssr 定义仅服务器模板,您将能够使用标准空格键语法呈现这些模板。

    您需要将您的服务器模板放在仅服务器 private 目录下,并使用以下命令在您的服务器代码中编译它们:

    SSR.compileTemplate("emailToCustomer", Assets.getText("emailToCustomer.html"));
    

    服务器模板不需要<template>标签,你可以直接定义它们:

    private/emailToCustomer.html

    <p>Hello {{name}}</p>
    <p>This is server-side rendering !</p>
    

    在您的服务器代码中,一旦模板被编译,您就可以像在标准客户端 Blaze 模板中一样定义助手:

    Template.emailToCustomer.helpers({
      name: function(){
        return this.firstName + " " + this.lastName;
      }
    });
    

    然后您可以使用以下方法渲染模板:

    var html = SSR.render("emailToCustomer", {
      firstName: "John",
      lastName: "Doe"
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-12
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      相关资源
      最近更新 更多