Search code examples
polymerpolymer-2.x

Templatizer - How to render multiple times same template, Polymer 2.x


In Polymer 1.x I was used to write a templatize code like this:

renderTemplate(query, properties) {
  let element = this.shadowRoot.querySelector(query);
  this.templatize(element);
  var instance = this.stamp(properties);
  return instance;
}

which worked well. But in Polymer 2.x there is a new error message A <template> can only be templatized once. Well it doesn't make sense, because I have 1 template which I want to redistribute multiple times with different properties.

I am giving here an example of how is my code

I have #template1 and #template2 I want to render #template1 then #template2 then #template1.

In steps how I render templates:

1) templatize #template1

2) stamp properties

3) templatize #template2

4) stamp properties

5 a) templatize #template1 => ERROR

5 b) skip templatize and stamp properties => #template2 is rendered....

How am i able to make this possible? calling stamp() after rendering #template2 will result in another #template2 render. I want #template1, but I can't templatize #template1 because it has been already templatized. And stamp is always "binded" to last templatized element.

Am I doing something wrong? I do really hate Polymer because of it's bad documentation and hard to google something usefull


Solution

  • I found a workaround which is propably not the best solution but it works. I tried to search in source code for some solutions but there wasn't anything usefull except the one property called __templatizeOwner. This property is set to all templatized elements. Removing this property from an element is the way.

    renderTemplate(query, properties) {
      let element = this.shadowRoot.querySelector(query);
      if(element.__templatizeOwner) {
        element.__templatizeOwner = null;
      }
      this.templatize(element);
      var instance = this.stamp(properties);
      return instance;
    }
    

    I am not sure what side effects this might have (more memory usage or something) but this is the only way I was able to find out.