Lit-Element:从 属性 字符串输出原始 HTML

Lit-Element : Outputting Raw HTML from Property String

我是 Lit-Element 的新手,在作为 属性 字符串传递时无法输出原始 HTML。我猜想有更好的方法可以完成此任务,我们将不胜感激。

JS Fiddle 在这里显示我的问题: https://jsfiddle.net/32dnvkwq/

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>

<script type="module">
  import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';

  class MyElement extends LitElement {

      static get properties() { 
        return { str: String }
     }

    render() {
      return html `${this.str}`;
    }  
  }

  customElements.define('my-element', MyElement);
</script>

<my-element str="line1<br />line2"></my-element>

输出:

line1<br />line2

我想出了一个使用文档片段的解决方法。不确定它是否理想,但它按预期工作。

JS Fiddle 显示解决方案:https://jsfiddle.net/1whj0cdf/

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>

<script type="module">
  import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';

  class MyElement extends LitElement {

      static get properties() { 
        return { str: String }
     }

    returnString() {
        var frag = document.createRange().createContextualFragment(`${ this.str }`);
      return frag;
    }

    render() {
      return html `${ this.returnString() }`;
    }  
  }

  customElements.define('my-element', MyElement);
</script>

<my-element str="line1<br />line2"></my-element>

这是一个危险的操作,因此您必须明确 opt-in 以允许渲染 HTML。确保您的 HTML 是安全的并且不是由用户设置的。您必须从 lit-html 导入 unsafeHTML directive 并将 this.str 包装在其中。

<script src="https://unpkg.com/@webcomponents/webcomponentsjs@next/webcomponents-loader.js"></script>

<script type="module">
  import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';
  import {unsafeHTML} from 'https://unpkg.com/lit-html@latest/directives/unsafe-html.js?module';

  class MyElement extends LitElement {

      static get properties() { 
        return { str: String }
     }

    render() {
      return html `${unsafeHTML(this.str)}`;
    }  
  }

  customElements.define('my-element', MyElement);
</script>

<my-element str="line1<br />line2"></my-element>