Simple JavaScript Templating


You should avoid writing HTML in Javascript code because it can be difficult to modify and maintain. For example, this can get messy, unwieldy and very easy to accidentally cause syntax errors:

Instead, consider using a template.

HTML template

Write your HTML template in a <script> tag with the type set to text/template. This prevents the browser from rendering or attempting to run the template. Make sure it has a unique ID.

Write in variables surrounded with % characters. This is so we can identify them later to be replaced by Javascript.

Template function

This function takes two arguments:

  • templateid: the ID of the template to use (e.g. “my-template”)
  • data: an object containing the values to be entered into the template where the keys match the template variables and their keys being the values to enter (e.g. {title:"MYTITLE", summary:"MYSUMMARY"})

This function does the following:

  • Expects templateid to be the id of an existing element.
  • Expects data to be an object with the data.
  • Uses two parameters in replace to do the substitution:
    • The first is a regular expression that searches for all %keys%. The key can be a combination of A-Z, a-z, 0-9 and underscore _.
    • The second is an anonymous function that gets called for every match. It searches the data object for the key that the regex found. If the key is found in the data, then the value of the key is returned and that value will be replacing the key in the final output. If the key isn’t found, an empty string is returned.


Leave a Reply

Your email address will not be published. Required fields are marked *