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:
1 2 3 4 5 6 7 8 | <script id="template-table-row" type="text/template"> <li style="width:5000px;"> <span style="display:inline-block;width:500px;">{{Dept}}</span> <span style="display:inline-block;width:500px;">{{Name}}</span> <span style="display:inline-block;width:480px;">{{Title}}</span> <span>{{Office}}</span> </li> </script> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function displayResults(data) { var tb = $("#carouselInner"); tb.html(""); var final = ""; var table = ""; for (var i = 0; i < data.Staff.length; i++) { var template_row = document.getElementById("template-table-row"); var templateHtml_row = template_row.innerHTML; table += templateHtml_row.replace(/{{Dept}}/gi, data.Staff[i].Department) .replace(/{{Name}}/gi, data.Staff[i].Name) .replace(/{{Title}}/gi, data.Staff[i].Title) .replace(/{{Office}}/gi, data.Staff[i].Office); } var template = document.getElementById("template-page"); var templateHtml = template.innerHTML; final += templateHtml.replace(/{{tbody}}/g, table); tb.html(final); } |
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.