我希望使用聚合物和飞镖制作一个通用列表。我正在扩展UL元素。我想将模板变量放在此自定义元素的内容中。
<ul is="data-ul">
<li>{{item['first_name']}}</li>
</ul>
自定义元素
<polymer-element name="data-ul" extends="ul">
<template repeat="{{item in items}}">
<content></content>
</template>
<script type="application/dart" src="data-ul.dart"></script>
</polymer-element>
我期待模板变量被插值,但它只是按原样输出到DOM。如何输出要呈现为模板的内容标记而不仅仅是直接输出?
不幸的是,这里有两个问题。
<content>
不能这样使用。它是一个占位符,用于在Shadow DOM中的特定位置渲染轻型DOM节点。首先 <content>
选择节点,赢[1]。像你一样冲压掉一堆,虽然非常直观,但不会按预期工作。
您将聚合物的内部世界与元素外部的外部世界混合在一起。这实际上意味着绑定(例如 {{}}
)只能在上下文中工作 <polymer-element>
。
你可以做的一件事就是创建一个分布式轻DOM子项的副本 items
你元素的属性。在JavaScript中,这看起来像:
<template repeat="{{item in items}}">
<li>{{item['first_name']}}</li>
</template>
<content id="content" select="li"></content>
<script>
Polymer('data-ul', {
ready: function() {
this.items = this.$.content.getDistributedNodes();
}
});
</script>
注意:我用过的唯一原因 <content select="li">
是确保元素只接受 <li>
节点。如果您不担心用户使用其他类型的元素,请使用 this.items = [].slice.call(this.children);
。
要做到这一点,你应该覆盖 parseDeclaration
方法。此方法负责解析/创建将绑定的所需html。例如,假设您有下一个模板
<polymer-element name="data-ul" extends="ul" attributes="items">
<template>
<template repeat="{{item in items}}" ref="itemTemplate"></template> <!-- this is the replacement of content tag -->
</template>
<script type="application/dart" src="data-ul.dart"></script>
</polymer-element>
或者,如果您想要一些默认元素:
<polymer-element name="data-ul" extends="ul" attributes="items">
<template>
<template repeat="{{item in items}}">
<!-- Def elements -->
<template bind="{{item}}" ref="itemTemplate"></template> <!-- this is the replacement of content tag -->
<!-- Def elements -->
</template>
</template>
<script type="application/dart" src="data-ul.dart"></script>
</polymer-element>
那你应该有下一堂课:
@CustomTag('data-ul')
class DataUl extends LiElement with Polymer, Observable {
DataUl.created() : super.created();
@published List items;
void parseDeclaration(Element elementElement) {
// We need to remove previous template from element.templateContent
// in that way it no continues adding a new content every time that we instantiate
// this component.
var previousTemplate = element.templateContent.querySelector('template#item');
if(previousTemplate != null)
previousTemplate.remove();
var t = this.querySelector('#itemTemplate'); // Gets the template with id itemTemplate from the content html
if(t != null) // if not null
element.templateContent.append(t); // append itemTemplate to element.templateContent
else
element.templateContent.append(new TemplateElement()..id='itemTemplate'); //if no template is added append an empty template to avoid errors
super.parseDeclaration(elementElement); // call super
}
}
最后使用自定义元素如下:
<ul is="data-ul" items="{{[{'first_name': 'jay'}, {'first_name': 'joy'}]}}">
<template id="itemTemplate">
<li>{{item['first_name']}}</li>
</template>
</ul>