template.js

From Template library from Messages app now available in shared/js

Rick Waldron post the new template.js library that works originally for gaia/cummunication apps. Now it’s widely adopted for other apps such as settings. The template.js library is pretty small and stable for general use. just copy it and put in your library to use it. The syntax is no magic, just inject an single id tag into main html file. And the ‘template’ is just the commented code. It allows general parameters replacement and prevent innerHTML pollution. Here’s the post from Rick: Using the Template library is simple:

1. Add <script src=“shared/js/template.js”></script> to your index.html

2. Create your template as a comment node inside of any type of element, place in index.html:

  <span id=“emphasis-template”>   <!-- <${tag}>${value}</${tag}> -->   </span>

  <span id=“greeting-template”>   <!-- Hello ${name}! -->   </span>

3. In your JavaScript code, initialize an instance of this template:

  // Template will accept either an id string or a node!   var emphasis = new Template(‘emphasis-template’);   var greeting = new Template(document.getElementById(‘greeting-template’));

4. Generate a safe markup string with specified values by calling the interpolate method of the template object:

  greeting.interpolate({     name: ‘World’   });

  // Hello World!

Simple partial nesting is supported, just tell interpolate which properties are “safe”:

  var name = emphasis.interpolate({     tag: ‘b’,     value: ‘World’   });

  // we know that the value of ‘name’ has already been escaped 😃   greeting.interpolate({ name: name }, { safe: [‘name’] });

  // Hello <b>World</b>!

Markup strings produced by Template are innerHTML safe (unless explicitly marked otherwise, as shown above):

  greeting.interpolate({     name: ‘<script>alert(“hi!”)’ + ‘</script>’   });

  // &lt;script&gt;alert(&quot;hi!&quot;)&lt;/script&gt;

Template instances disallow modification of the template string once the object is initialized, but the toString() method will return the raw template as a string:

  greeting.toString();

  // Hello ${name}!

  emphasis.toString();

  // <${tag}>${value}</${tag}>

It’s important to remember that Template and WebComponent are not at odds with each other and exist to serve to different purposes; read more here: https://bugzilla.mozilla.org/show_bug.cgi?id=908950#c6