Ember.js在静态HTML中呈现多个视图

Ember.js Render multiple views inside static HTML

本文关键字:视图 js 静态 HTML Ember      更新时间:2023-09-26

我是Ember的新手,一直在尝试渲染视图。上下文中的应用程序不是一个单页应用程序,但到目前为止,Ember一直表现得很好,直到我开始处理视图。

我试图在一个页面上呈现多个视图(这就像一个面板,有大量的静态HTML和几个容器,每个视图一个)。

示例HTML:假设我想呈现两个列表,一个在"左容器"div中,另一个在右容器中。

<div class="static-header></div>
<!-- more static content goes here -->
<div id="left-container"></div>
<!-- more static content goes here -->
<div id="right-container"></div>
...

我尝试过创建不同的视图并使用appendTo方法插入它们(在Ember指南的"定义视图"一节中进行了描述),但它抛出了错误:

查找视图模板时找不到容器。这很可能是由于手动实例化Ember.View。请参阅:http://git.io/EKPpnA

我找不到使用它指向的链接的路。

徽章代码:

var App = Ember.Application.create({});
App.HomeViewLeft = Ember.View.extend({    
    templateName: 'home-left',
});
var view = App.HomeViewLeft.create();
view.appendTo('#left-container');

我还尝试过使用Ember api文档中描述的ContainerView:

App.HomeViewLeft = Ember.View.extend({    
    templateName: 'home-left',
});
var containerView = Ember.ContainerView.create({
classNames: ['container-view'],
});
containerView.pushObject(App.HomeViewLeft.create());
containerView.appendTo('left-container');

但我也犯了同样的错误。

我应该如何分别在#left容器和#right容器中渲染每个视图?提前谢谢。

模板:

<div id="here"></div>
<script type="text/x-handlebars" data-template-name="components/my-foo">
  {{text}}
</script>

JS:

App = Ember.Application.create({});
Ember.Application.initializer({
  name: 'stand-alone-components',
  initialize: function(container, application) {
    App.MyFooComponent.create({text: 'Hello World', container: container}).appendTo('#here');
  }
});
App.MyFooComponent = Ember.Component.extend({
  init: function() {
    this._super();
    this.set('layout', Ember.TEMPLATES['components/my-foo']);
  }
});

http://emberjs.jsbin.com/nekowidera/1/edit?html,js,输出

看起来你正试图让视图表现得像部分

将任何静态内容移动到部分中,并将其包含在主模板中,如下所示:

{{partial "header"}}

要渲染的列表可以变成一个组件(如果其中唯一更改的是数据)。

因此,您最终得到一个包含部分和组件的单一视图:

<div class="static-header>{{partial "header"}}</div>
{{partial "static-content"}}
<div id="left-container">{{list-component data=firstList}}</div>
{{partial "static-content"}}
<div id="right-container">{{list-component data=secondList}}</div>
...