Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

dart - Bind content containing html tags

How can I display content containing html tags like <br> inside a polymer-element like:

<polymer-element name="my-element">
  <template>
    {{mylongtext}}
  </template>
<script ...></script>
</polymer-element>
@CustomTag("my-element")
class MyElement extends PolymerElement {
  @observable string mylongtext = "bla bla <br> bla bla <strong> bla </strong>";
}

Currently those tags are shown as text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you mention, mylongtext is simply displayed as a string, it's not specifically an element or even mark up. However what we can do is automatically call a function any time that our observable is changed. In the callback we create a DocumentFragment which is based off of the contents of the string, and then insert that into our div container.

<polymer-element name="my-element">
  <template>
    <div id="container">

    </div>
  </template>
<script ...></script>
</polymer-element>
@CustomTag("my-element")
class MyElement extends PolymerElement {
  @observable string mylongtext = "bla bla <br> bla bla <strong> bla </strong>";

  MyElement() {
    // Bind property changes to the mylongtext observable string and 
    onPropertyChange(this, #mylongtext, addFragment);
  }

  // Need to do it on inserted to ensure we add the initial value.
  void inserted() {
    super.inserted();
    addFragment();
  }

  void addFragment() {
    var df = new DocumentFragment.html(mylongtext);
    // In the clear any contents from container and add new fragment
    $['container'].nodes..clear()..add(df);
  }

}

Note that onPropertyChange and the $[..] automatic node finding require Polymer dart 0.8.0 or higher (in previous versions it's bindProperty and using shadowRoot.query(..) respectively).

One thing to keep in mind however, is that using DocumentFragment.html() and other similar string-to-html parsers is that they are subject to Sanitization as discussed in this breaking change.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...