3

I have a trusted html file with data-bindings, which I want to include to a web component.I tried multiple ways to include the html file, but the data-binding doesn't work. I know polymer won't stamp the html, because it becomes a vulnerability for XSS attacks from untrusted sources, but I have a trusted source.

I'm already aware of 1 and 2 and tried out juicy-html, iron-ajax with inner-h-t-m-l and also the injectBoundHTML function.

Is there other way than binding everything by myself?

The file I want to include contains input fields and it is a predefined form.

Community
  • 1
  • 1
aphex
  • 3,372
  • 2
  • 28
  • 56

1 Answers1

2

You can use the Templatizer by creating a <template> manually and setting its content. The important part is that you can't just set the innerHTML

Polymer({
  is: 'my-elem',
  behaviors: [ Polymer.Templatizer ],
  ready: function() {

    var template = document.createElement('template'); 
    
    // you must prepare the template content first (with bindings)
    var templateContent = document.createElement('div');
    templateContent.innerHTML = 'First: <span style="color: red">[[person.first]]</span> <br> Last: <span style="color: green">[[person.last]]</span>';
    
    // and cannot simply set template's innerHTML
    template.content.appendChild(templateContent);
    
    // this will process your bindings
    this.templatize(template);        
    var person = {
      first: 'Tomasz',
      last: 'Pluskiewicz'
    };
    var itemNode = this.stamp({ person: person });
    
    Polymer.dom(this.root).appendChild(itemNode.root);
  }
});
<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.19/webcomponents.min.js"></script>
    <link rel="import" href="https://raw.githubusercontent.com/Polymer/polymer/master/polymer.html" />
  </head>

  <body>
    <my-elem>
    </my-elem>
       
    <dom-module id="my-elem">
      <template>
      </template>  
    </dom-module>
  </body>

</html>
Tomasz Pluskiewicz
  • 3,622
  • 1
  • 19
  • 42
  • I tried out your snippet and it works. The data binding inside the template is working. Is it possible to stamp complex objects? Also there is no data binding with the outer elements. The stamping is only in one direction. var itemNode = this.stamp({ i: this.data }); data = { name = "Alex" } – aphex Oct 06 '16 at 14:01
  • 1
    Yes, you can bind any object (see update). Two way binding is possible but tricky. See this bin: http://jsbin.com/kipato/edit?html,js,output – Tomasz Pluskiewicz Oct 06 '16 at 14:14
  • Thank you for the examples. The data binding works now :) Do you know how to pass also the events? The fields are firing events, but the outer context doesn't see them. – aphex Oct 07 '16 at 10:02
  • 1
    I found the problem. The element fires an event on ready state when I create it. I changed that to attached and now it works fine :) Thank you very much for your help! – aphex Oct 07 '16 at 11:46