Javascript templating example (vanilla)

snippet

Originally posted as GitHub Gist on 16 May 2017 (details)


Source: https://gist.github.com/paulera/77e281334ff47b24625f3eb404a7e268

Description: Example of javascript templating using {placeholders}. No framework, just pure js.


js-html-templating.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<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>