Last active
September 22, 2022 00:32
-
-
Save paulera/77e281334ff47b24625f3eb404a7e268 to your computer and use it in GitHub Desktop.
Example of javascript templating using {placeholders}. No framework, just pure js.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <body> | |
| <!-- Adapted from http://codoki.com/2015/09/01/native-javascript-templating/ --> | |
| <!-- Implemented Marcos Correia's suggestion - refer to article comments --> | |
| <ul id="list"></ul> | |
| <script id="my-template" type="x-template"> | |
| <span class="movie-name">{name}</span>: | |
| <span class="movie-rating">{rating}</span> | |
| </script> | |
| <script> | |
| // Simple array of movies | |
| var movies = [ | |
| { "name" : "Inception", "rating": "4" }, | |
| { "name" : "Goodfellas", "rating": "5" }, | |
| { "name" : "Fight Club", "rating": "4" }, | |
| ]; | |
| // Loop through the movie array and append each list item | |
| movies.forEach(function(movie) { | |
| // get template from tag | |
| var template = document.getElementById("my-template").innerHTML; | |
| // replace placeholders with values from movie object | |
| for (var key in movie) { | |
| template = template.replace (new RegExp("{"+key+"}", 'g'), movie[key]); | |
| } | |
| // add to the list | |
| el = document.createElement('li'); | |
| el.innerHTML = template; | |
| document.getElementById("list").appendChild(el); | |
| }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment