代码之家  ›  专栏  ›  技术社区  ›  Kent Wood

如何在polymer3模板中嵌入html代码(如unsafeHTML)

  •  0
  • Kent Wood  · 技术社区  · 7 年前

    please check the plunker

    static get template() {
       return html`
         <p>This content is from ChildClass.</p>
         <p>${super.template}</p>
         <p>Hello again from ChildClass.</p>
         <p style='color:red'>[[partHtml]] <==== this should be 'hello'</p>
         `;  
     }
     get partHtml()
     {
       return "<span>hello</span>";
     }
    

    我想要 partHtml 像普通的HTML一样被注入到模板中。

    我知道lit元素中不安全的HTML可以做到这一点,但是lit元素不能使用 super.render() 东西,它不像高分子元素那样方便。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Hyyan Abo Fakher JM1    7 年前

    用一下怎么样 inner-h-t-m-l 属性

    static get template() {
       return html`
         <p>This content is from ChildClass.</p>
         <p>${super.template}</p>
         <p>Hello again from ChildClass.</p>
         <p style='color:red' inner-h-t-m-l="[[partHtml]]"></p>
         `;  
     }
     get partHtml()
     {
       return "<span>hello</span>";
     }
    
        2
  •  1
  •   Hyyan Abo Fakher JM1    7 年前

    可以使用多行字符串

    static get template() {
      return html`
       <p>This content is from ChildClass.</p>
       <p>${super.template}</p>
       <p>Hello again from ChildClass.</p>
       <p style='color:red'>${this.partHtml}</p>
     `;  
    }
    static get partHtml() {
      return html`<span>hello</span>`;
    }
    

    Test on Plnkr

        3
  •  0
  •   Hyyan Abo Fakher JM1    7 年前

    最后,我在调试调用堆栈时找到了答案。 只是使用 htmlLiteral ,密钥代码如下

    import {PolymerElement, html} from 'https://unpkg.com/@polymer/polymer@3.0.5/polymer-element.js'
    import {htmlLiteral} from 'https://unpkg.com/@polymer/polymer@3.0.5/lib/utils/html-tag.js'
    
    ....
    
      static get template() {
          return html`<p style='color:red'>${this.partHtml} <==== this should be 'hello'</p>`;  
      }
      static get partHtml()
      {
        return htmlLiteral `<span>hello</span>` ;
      }
    
    推荐文章