Динамическая загрузка HTML-страницы с помощью Polymer importHref

Я пишу простой элемент, загружающий html-файлы с помощью вспомогательной функции Polymer 1.0 importHref(). Страница загружается, но вместо HTML-рендеринга на страницу я получаю [object HTMLDocument].

Когда я регистрирую успешный обратный вызов, импортированная страница оборачивается в объект #document (не уверен в терминологии здесь). Но вся информация есть в консоли.

Итак, мой вопрос: как мне отобразить html на странице?

элемент:

<dom-module id="content-loader">

<template>
    <span>{{fileContent}}</span>
</template>

<script>

Polymer({

    is: "content-loader",

    properties: {
        filePath: {
            type: String
        }
    },

    ready: function() {
        this.loadFile();
    },

    loadFile: function() {
        var baseUrl;

        if (!window.location.origin)
        {
            baseUrl = window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
        }
        else
        {
            baseUrl = window.location.origin;
        }

        //import html document and assign to fileContent
        if(this.filePath)
        {
            this.importHref(baseUrl + this.filePath, function(file){
                this.fileContent = file.target.import;
                console.log(this.fileContent); //logs fine
            },
            function(error){
                console.log(error);
            });
        }
    }

});

</script>

in use:

<content-loader file-path="/app/general/contact.html"></content-loader>

person anthony    schedule 25.06.2015    source источник


Ответы (1)


<span>{{fileContent}}</span> преобразует fileContent в строку, поэтому вы видите [object HTMLDocument] (это то, что вы получаете, когда вызываете toString() для объекта document).

В общем, Polymer не позволит вам привязываться к HTML или содержимому узла, потому что это угроза безопасности.

fileContent у вас есть document, что означает, что это набор узлов DOM. То, как вы используете этот документ, зависит от того, какой контент вы загрузили. Один из способов рендеринга узлов — добавить fileContent.body к вашему локальному DOM, например:

Polymer.dom(this.root).appendChild(this.fileContent.body);

Вот более полный пример (http://jsbin.com/rafaso/edit?html,output< /а>):

<content-loader file-path="polymer/bower.json"></content-loader>

<dom-module id="content-loader">

  <template>
    <pre id="content"></pre>
  </template>

  <script>

    Polymer({
      is: "content-loader",
      properties: {
        filePath: {
          type: String,
          observer: 'loadFile'
        }
      },

      loadFile: function(path) {
        if (this.filePath) {
          console.log(this.filePath);
          var link = this.importHref(this.filePath, 
            function() {
              Polymer.dom(this.$.content).appendChild(link.import.body);
            },
            function(){
              console.log("error");
            }
          );
        }
      }
    });

  </script>
</dom-module>
person Scott Miles    schedule 26.06.2015