Trevor Dixon
Trevor Dixon

Reputation: 24362

Polymer 1.0 template bind ref equivalent

In Polymer 0.5, you could do:

<template bind ref="howdyTpl"></template>
...
<template id="howdyTpl">Howdy {{whatever}}</template>

And the template with id 'howdyTpl' would get stamped where referenced in the ref attribute.

How can I do something similar in Polymer 1.0?

Upvotes: 0

Views: 1333

Answers (2)

Brandon
Brandon

Reputation: 570

I've created an element that resolves this problem. It's kind of a hack, but it works... including with multi-depth file inclusion and data binding that the other answer provided did not handle.

Upvotes: 1

Trevor Dixon
Trevor Dixon

Reputation: 24362

Here's a custom element that does something similar.

Polymer({
  is: 'bind-ref',

  properties: {
    ref: {
      type: String,
      observer: 'refChanged',
    },
  },

  refChanged: function(newRef, oldRef) {
    if (oldRef != undefined) {
      this._removeChildren();
      this._stamp();
    }
  },

  _stamp: function() {
    this._parent = Polymer.dom(this).parentNode;
    var rootEl = this._parent;
    while (Polymer.dom(rootEl).parentNode) {
      rootEl = Polymer.dom(rootEl).parentNode;
    }

    var tpl = Polymer.dom(rootEl).querySelector('#' + this.ref);
    var tplRoot = tpl.stamp().root;
    this._children = Array.prototype.slice.call(tplRoot.childNodes);
    Polymer.dom(this._parent).insertBefore(tplRoot, this);
  },

  _removeChildren: function() {
    for (var i = 0; i < this._children.length; i++) {
      Polymer.dom(this._parent).removeChild(this._children[i]);
    }
  },

  attached: function() { this._stamp(); },
  detached: function() { this._removeChildren(); },
});

The target template element must be a dom-template element.

<bind-ref ref="howdyTpl"></bind-ref>
<template is="dom-template" id="howdyTpl">Howdy <span>{{whatever}}</span></template>

(Code snippets licensed Apache 2.0.)

Upvotes: 1

Related Questions