Background: this question relates to development of an extension for recent versions of Chrome. It relies on javascript features such as HTML imports and custom elements that are not available on all browsers but that's OK for this case.
I'm trying to implement a HTML custom element simplified as follows:
<custom-el>
<span slot="head">Great</span>
<span slot="item">Item one</span>
<span slot="item">Item two</span>
<span slot="foot">done</span>
</custom-el>
I register the <custom-el>
. Each time the element is created, my code's custom element class attaches a shadow root and appends to the shadow root content from the following template:
<template id="main">
<h1><slot name="head"></slot></h1>
<ul>
<slot name="item"></slot>
</ul>
<i><slot name="foot"></slot></i>
</template>
I would like to redistribute each <span>
with attribute slot="item"
to a secondary template responsible for rendering an individual item:
<template id="sub">
<li><slot name="item"></slot></li>
</template>
The number of slots with attribute name="item"
is not fixed. It is generated from a database and changes regularly.
I understand that a slot can be redistributed by attaching a shadowRoot to the slot's parent element and setting the slot's slot attribute, e.g. <slot name="item" slot="newItem">
. But I don't think this will work in my case since the sub template needs to wrap each item instance, not the list of items.
I could attach shadow roots and sub templates to each item in the main document. This would work but my preference is that the main template import and apply any nested shadowRoots and templates. This way, the primary document need only import the file containing the main template. The implementation of the component's details is encapsulated in the main template html file.
I could also use the slotchange
event and the HTMLSlotElement.assignedNodes
method to cobble together a scripting solution. But I'd rather not go that way.
Is there another approach? My actual use case involves a more complex HTML structure. Or maybe my architecture or understanding of web components is flawed?
<span slot="item">
elements from the Light DOM. I expect long intervals between updates (multi-second). Is that what you're asking? - DAR