Using script templates with JavaScript to create dynamic HTML

Javascript to the rescue!

I wanted an easy way to create some dynamic HTML with JavaScript. I searched a few different ways to do this, but this was by far the easiest and cleanest way I have found so far to user script templates with JavaScript. You start with a script tag but with a type=”text/template” like the one below:

This should be on the page being loaded, otherwise the JavaScript will not find it.

From there it is simple as getting your data, iterating over the data. (I would suggest JSON) and then using replace to replace the specified parts. This can be done in following fashion:

I have one extra ‘replace’ at the end since I was making a table, but you could simply use jQuery to create divs with columns and format everything nice. When using script templates with JavaScript an important thing to notice is the formatting of the text to be replaced. This is a regular expression and the replace is looking to match it. the ‘g’ at the end makes it global and the ‘i’ makes it case insensitive. This may or may not be important to your application, but you should be aware of what these things are doing. There are more complex ways to do the regular expression and I would follow this tutorial.

One other tip I found was to iterate over the data in reverse to make the JavaScript faster. That is for another post on how and why that works faster. I didn’t use that tip here but you should think about how fast you need to display the data to the user. Usability is of the most importance for your users and for SEO.