Change template content at runtime

2019-08-04 16:36发布

问题:

I want to build Polymer element that generates a list output

<polymer-element name="polymer-list>
  <template>
    <template id="my-repeat" repeat="{{item in listData}}">
      <!-- use content here -->

      <!-- some fix dummy content to see how this is handled -->
      <div id="div_{{item['item']['index']}}">{{item['item']['index']}}</div> 

    </template>
    <content id="content" select="*"></content>
  </template>
  <script type="application/dart" src="polymer_list.dart"></script>
</polymer-element>

and I want to move the elements provided by <content select="*"></content> inside the <template id="my-repeat"> tag (at the position of <!-- use content here -->) when the polymer-list is initiated (ready, attached, ...).

My polymer-list should be used like

<polymer-list id="list" data="{{data}}" on-polymer-select="{{selectAction}}">
  <div class="header">{{item['index']}}</div>
  <div class="item {{item['selected']}}">Index: {{item['index']}}</div>
</polymer-list>

As result both <div>s should be repeated for each item in data by the <polymer-list> element.

I tried

var listContent = ($['content'] as ContentElement).getDistributedNodes();
var t = ($['my-repeat'] as TemplateElement);
listContent.forEach((n) => t.append(n.clone(true));
// listContent.forEach((n) => t.content.append(n.clone(true)); // didn't work either

as result I get

<!-- ... -->
<template id="my-repeat" repeat="{{item in listData}}">
  #document-fragment
    <div class="header"></div>
    <div class="item">Index: </div>
</template>
<div id="div_0">0</div>
<div id="div_1">1</div>
<div id="div_0">2</div>
<!-- ... -->

The fix dummy content is repeated normally but the dynamically added elements are placed inside a document-fragment but not repeated.

Any hint about manipulating the HTML at <!-- use content here --> at runtime would be great.

回答1:

Unfortunately you can insert you content only one time as specified in specification (http://www.w3.org/TR/2013/WD-components-intro-20130606/#insertion-points):

Insertion points let you reordered or selectively omit rendering the host's children, but they will not cause something to be rendered multiple times. Tree order dictates when each of these elements takes a pass at selecting the children. Once the child is selected to be rendered at one insertion point, it can't be claimed by another one, which is why the details-open decorator only renders the summary once.