HTML Tags Within Internationalized Strings In Polymer.dart

Update

A ready-to-use element for Dart Polymer 1.0 is bwu-bind-html


Update

Polymer now provides support for this out of the box

 this.injectBoundHTML('<div>your HTML goes here ${someBoundFieldValue}</div>);

Old

This is the code of the <safe-html> tag I’m using.

library safe_html;

import 'dart:async';
import "dart:html";

import "package:polymer/polymer.dart";


@CustomTag("safe-html")
class SafeHtml extends PolymerElement  {

  @published String model;

  NodeValidator nodeValidator;
  bool get applyAuthorStyles => true;
  bool isInitialized = false;

  SafeHtml.created() : super.created() {
    nodeValidator = new NodeValidatorBuilder()
    ..allowTextElements();
  }

  void modelChanded(old) {
    if(isInitialized) {
      _addFragment();
    }
  }

  void _addFragment() {
    var fragment = new DocumentFragment.html(model, validator: nodeValidator);
    $["container"].nodes
    ..clear()
    ..add(fragment);

  }

  @override
  void attached() {
    super.attached();
    Timer.run(() {
      _addFragment();
      isInitialized = true;
    });
  }
}
<!DOCTYPE html>

<polymer-element name="safe-html"> 
  <template>
    <div id="container"></div>
  </template>

  <script type="application/dart" src="https://stackoverflow.com/questions/20868296/safe_html.dart"></script>

</polymer-element>

usage:

<safe-html model="{{someField}}></safe-html>

Leave a Comment