流星 - 通过ajax返回HTML模板

时间:2014-03-08 23:11:20

标签: ajax api templates meteor handlebars.js

我想在另一个网站上显示我的Meteor应用程序中生成的模板。

我原本希望在网站上使用ajax调用来获取相关的流星模板和数据,但我很挣扎。

网站拨打以下电话:

<body>
  <div id="result">
</div>
</body>

<script>
  $( "#result" ).load( "http://myMeteorApp/get_template" );
</script>

在Meteor应用程序中,我尝试使用iron-router返回模板:

Router.map(function () {
  this.route('get_template', {
    where: 'server',
    path: 'get_template',   
    action: function () {
      return 'get_template'
    }
})

模板'get_template.html'位于'private'文件夹中。

<template name="get_template">    
  <table class="table table-hover table-condensed">
    <tr>
      <th>Name</th>
      <th>Email</th>      
      <th>Mobile</th>          
    </tr>
    {{#each members}}
    <tr>
      <td>{{first_name}} {{last_name}}</td>
      <td>{{email}}</td>
      <td>{{mobile}}</td>          
    </tr>
    {{/each}}
  </table>        

这不起作用,我有一种感觉,我正在咆哮错误的树。

也许我应该使用iframe?但我更喜欢Meteor应用程序的行为类似API,只需返回模板。

帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

https://github.com/EventedMind/iron-router#server-side-routing

  

服务器操作函数(RouteControllers)具有不同的属性   和方法。即,服务器上没有呈现   爱好。

此外,即使这项工作正常,您的javascript中也会遗漏很多内容:

  • 您似乎没有指定模板中使用的数据
  • action函数返回一个字符串。这应该做什么?

我认为您最好的选择是使用服务器端模板引擎,例如meteor-handlebars-server,只需手动呈现模板:

Router.map(function () {
  this.route('serverFile', {
    where: 'server',
    path: '/get_template/:templatename',

    action: function () {
      var templatename = this.params.templatename;
      this.response.writeHead(200, {'Content-Type': 'text/html'});
      this.response.end(Handlebars.templates[templatename]({members: []}));
    }
  });
});

将数据插入所提供对象的members字段中。