如何在EmberJS中渲染除application.hbs之外的模板?

Mel*_*vin 7 templates ember.js

在EmberJS中,主模板文件是application.hbs.从路径呈现的任何模板{{outlet}}都是此主模板文件的模板.

现在,我有另一个主模板文件,比如print.hbs其中模板设计与application.hbs非常不同.我该怎么做呢?

在路由器文件中,我有:

App.Router.map(function() {

    this.resource('print', function() {
        this.route('display1');
        this.route('display2');
    });

    this.route('dashboard', {path: '/'});
    this.route('anything');
});
Run Code Online (Sandbox Code Playgroud)

路线dashboardanything使用application.hbs.我该怎么做才能print.hbsprint路线上使用?请帮忙.

pan*_*a82 4

您无法轻松更改应用程序模板。Ember 不会侦听templateName属性更改,并且当您尝试自己重新渲染模板时响应很差。

实现此目的的一个好方法是根据您处于“屏幕”模式还是“打印”模式,在应用程序模板中使用不同的部分。

  <script type="text/x-handlebars">
    {{#if isPrint}}
      {{partial "application-print"}}
    {{else}}
      {{partial "application-normal"}}
    {{/if}}
  </script>

  <script type="text/x-handlebars" data-template-name="application-normal">
    <div id="app-normal">
      <h2>Normal template</h2>

      {{outlet}}
    </div>
  </script>

  <script type="text/x-handlebars" data-template-name="application-print">
    <div id="app-print">
      <h2>Print template</h2>

      {{outlet}}
    </div>
  </script>
Run Code Online (Sandbox Code Playgroud)
App.ApplicationController = Ember.Controller.extend({
  isPrint: false,
  currentPathChange: function () {
    var currentPath = this.get("currentPath");
    var isPrint = currentPath ? currentPath.indexOf("print") === 0 : false;
    this.set("isPrint", isPrint);
  }.observes('currentPath').on("init")
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个 JSBin将演示为什么这也不起作用。根据这个错误报告,当同一页面中有多个outlet指令时,Ember 的把手会变得混乱,即使它们位于不同的#if范围内。

在这个问题得到解决之前,我提出以下稍微修改的解决方案。

申请模板为空。普通部分和打印部分各一个模板。

  <script type="text/x-handlebars">
    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="normal">
    <div id="app-normal">
      <h2>Normal template</h2>

      {{outlet}}
    </div>
  </script>

  <script type="text/x-handlebars" data-template-name="print">
    <div id="app-print">
      <h2>Print template</h2>

      {{outlet}}
    </div>
  </script>
Run Code Online (Sandbox Code Playgroud)

在路由器中,一切都进入正常资源和打印资源。普通资源放在/处,这样所有的链接都保持不变。无需在 ApplicationController 中进行特殊编码。

App.Router.map(function() {
  this.resource("print", function () {
    this.route("a");
    this.route("b");
  });

  this.resource("normal", {path: "/"}, function () {
    this.route("a");
    this.route("b");
  });
});
Run Code Online (Sandbox Code Playgroud)

在这里工作 jsbin 。