如何使用CompositeView在模板中添加静态html内容

Backbone.Marionette - How to add static html content in template using CompositeView?

本文关键字:添加 静态 html 内容 何使用 CompositeView      更新时间:2023-09-26

我是Marionette的新手。我开始了解Marionette复合视图。我不知道我是错了还是写了。

我的问题是,如何在模板上保留一些静态的html内容?

我的复合视图模板:

<script type="text/template" id="angry_cats-template">
        <div><a href="#logout">Click to logout</a></div> // i would like to add some static html here.
        <thead>
            <tr class='header'><th>Name</th></tr>
        </thead>
        <tbody></tbody>
    </script>
    <script type="text/template" id="angry_cat-template">
        <td><%= name %></td>
    </script> 

我是这样渲染的:

myApp = new Backbone.Marionette.Application();
      myApp.addRegions({
        mainRegion:"#content"
      });
      AngryCat = Backbone.Model.extend({});
      AngryCats = Backbone.Collection.extend({
          model:AngryCat
      });
      AngryCatView = Backbone.Marionette.ItemView.extend({
          template:"#angry_cat-template",
          tagName:'tr',
          className:'angry_cat'
      });
      AngryCatsView = Backbone.Marionette.CompositeView.extend({
          tagName:"table", //how to avoid my logout should  not append with table?
          id:"angry_cats",
          className: "table-striped table-bordered",
          template: "#angry_cats-template",
          itemView: AngryCatView,
          appendHtml: function(collectionView, itemView){
              collectionView.$("tbody").append(itemView.el);
          }
      });
      myApp.addInitializer(function(options){

          var cats = new AngryCats([
              { name: 'Wet Cat' },
              { name: 'Bitey Cat' },
              { name: 'Surprised Cat' }
          ]);
          var angryCatsView = new AngryCatsView({
              collection: cats
          });
             myApp.mainRegion.show(angryCatsView);
      });
      $(document).ready(function(){
          myApp.start();
      });

有人帮我吗?

实时演示

您必须从CompositeView中删除classNametagName,并按照以下更新复合模板

   <div><a href="#logout">Click to logout</a></div> // Now i am out.
    <table class="table-striped table-bordered">
      <thead>
        <tr class='header'><th>Name</th></tr>
      </thead>
      <tbody></tbody>
   </table>

此外,您不需要在CompositeView中具有appendHtml。取而代之的是简单的集合itemViewContainer: "tbody",其中项目视图将被附加。

请结账http://jsfiddle.net/fizerkhan/y6nH5/

您的错误可能在AngryCatsView appendHtml:function()中
您不应该需要此功能
要为Marionette指定要将子元素渲染到的div,请使用

itemView: AngryCatView
itemViewContainer: "tbody"

我写了一篇关于在TypeScript中使用Marionette的教程风格的博客。