3
votes

I have a scenario where I would like to create dynamic template elements that will be used with Polymer's dom-repeat.

My current prototype is the following (JSbin demo):

var domRepeat = document.createElement('template', 'dom-repeat');
domRepeat.items = ['a', 'b', 'c'];
var div = domRepeat.content.ownerDocument.createElement('div');
div.innerHTML = '[[item]]';
domRepeat.content.appendChild(div);
document.body.appendChild(domRepeat);
Polymer.dom.flush();

However, this does not work as intended. The output is:

[[item]]
[[item]]
[[item]]

rather than:

a
b
c

Since the [[item]] is printed out 3 times, I guess the dom-repeat itself works, but the data binding does not.

Plot twist: but if I change the example from dom-repeat to dom-bind, then the data binding does work. Changed example, inspired by this answer (JSBin demo):

var domBind = document.createElement('template', 'dom-bind');
domBind.item = 'Hello World!';
var div = domBind.content.ownerDocument.createElement('div');
div.innerHTML = '[[item]]';
domBind.content.appendChild(div);
document.body.appendChild(domBind);
Polymer.dom.flush();

The output is Hello World!, as expected.

Any ideas on how to get the first example to work?

1

1 Answers

3
votes

Binding in dynamically created HTML isn't that easy currently. I think there are plans to support this better eventually.

In the meantime Templatizer should allow to implement such a scenario. I haven't used it myself and haven't found code examples. iron-list and dom-if, dom-bind, dom-repeat seem to make use of it which might work as template for custom implementations.

https://github.com/Polymer/polymer/blob/master/src/lib/template/templatizer.html

This might help http://t-code.pl/blog/2015/08/polymer-templatizer/