使用来自 iron-router 服务器路由的数据渲染模板

Rendering templates with data from iron-router server route

我是 Meteor.js 的新人,有一个基本问题。我想用 iron-router 模块的服务器端路由数据渲染一个模板。我在我的路由选项中使用了 where: 'server'(来自 this link),但未触发渲染函数(this.render())。

我通过使用 NodeJS 请求和响应对象(如上例)成功完成了此操作,但我想将数据传递到模板并从服务器呈现模板。

这是我的路线代码:

Router.route('/movie/title', function () {

    var request = Meteor.npmRequire('request');
    var future = new (Npm.require('fibers/future'))();

    request('http://www.google.com', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            future.return(body);
        }
        else {
            future.throw(error);
        }
    })

    var myResult = future.wait();
    console.log(myResult);
    this.render('test', {
        data: { result: myResult }
    });
}, { where: 'server' });

这是我的模板代码:

<head>
  <title>Search your favorite movie</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  {{> hello}}

</body>

<template name="hello">
  <button>Click Me</button>
  <p>You've pressed the button {{counter}} times.</p>
</template>

<template name="test">
{{result}}
</template>

请指导我。

来自 Iron Router Cheatsheet,渲染在服务器上不可用:

# When you define a server route (via where: 'server'), you need to define the action function, and use in a fairly simplistic way, much like express.
# The render method is not available.

它似乎已经 6 个月没有更新了,我在 Iron Router Guide or the readme on GitHub 中找不到任何关于它只在客户端可用的信息,但我猜这就是问题所在。

如果您确实需要从服务器渲染,您也可以查看 meteorhacks:ssr (server-side rendering); there appears to be a pretty in-depth post about it on the meteorhacks site

从该包的自述文件来看,解决您的特定问题的方法似乎是在 private/ 目录中定义您的模板,然后在服务器上调用 compileTemplate 方法:

<!--template in private/hello.html-->
<template name="hello">
  <button>Click Me</button>
  <p>You've pressed the button {{counter}} times.</p>
</template>

<!--Another template in private/test.html -->
<template name="test">
  {{result}}
</template>

您还需要在服务器上定义任何助手,并在服务器上编译模板:

// in server/test.js
SSR.compileTemplate('test', Assets.getText('test.html')

然后您可以使用 SSR 包在服务器上使用数据呈现模板,这将 return HTML 作为字符串;您可以使用 Meteor 方法实现它以将 HTML 返回给客户端:

// You can call this method from the client to get the rendered template back:
Meteor.methods('renderTest', function(data) { 
  return SSR.render('test', data);
});

有关结合使用 SSR 和 iron:router 的更多详细信息,请参阅 this question