1. Code
  2. JavaScript

Quick Tip: Create a Makeshift JavaScript Templating Solution

Scroll to top
2 min read

Sometimes, you don't require a high-quality templating solution, but still need to keep from mixing lots of nasty HTML into your JavaScript. In these cases, a simple, makeshift templating system can go a long way.

Choose 720p for the best clarity.
Subscribe to our YouTube channel for more training.

Final Source

HTML

1
2
<!doctype html public 'ahh hell yeah'>
3
<html>
4
<head>
5
	<meta charset=utf-8>
6
	<title>Simple Templating</title>
7
</head>
8
<body>
9
  
10
  <div class="result"></div>
11
  
12
  <script type="template" id="template">
13
    <h2> 
14
      <a href="{{href}}">
15
        {{title}} 
16
      </a>

17
    </h2>

18
    <img src="{{imgSrc}}" alt="{{title}}">
19
  </script>
20
21
</body>
22
</html>

JavaScript

1
2
;(function() {
3
  // simulates AJAX request

4
  var data = [
5
    {
6
      title: "Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5",
7
      href: "https://code.tutsplus.com/tutorials/create-a-sticky-note-effect-in-5-easy-steps-with-css3-and-html5--net-13934

8
      imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/771_sticky/sticky_notes.jpg"

9
    },
10
    {
11
      title: "Nettuts+ Quiz #8",
12
      href: "https://code.tutsplus.com/articles/nettuts-quiz-8-abbreviations-darth-sidious-edition--net-23152

13
      imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/989_quiz2jquerybasics/quiz.jpg"

14
    },
15
    {
16
      title: "WordPress Plugin Development Essentials",
17
      href: "https://code.tutsplus.com/tutorials/wordpress-plugin-development-essentials--net-23135

18
      imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/1101_wpPlugins/wpplugincourse.png"

19
    }    
20
  ],
21
      template = document.querySelector('#template').innerHTML,
22
      result = document.querySelector('.result'),
23
      i = 0, len = data.length, 
24
      fragment = '';
25
  
26
  for ( ; i < len; i++ ) {
27
    fragment += template
28
      .replace( /\{\{title\}\}/, data[i].title )
29
      .replace( /\{\{href\}\}/, data[i].href )
30
      .replace( /\{\{imgSrc\}\}/, data[i].imgSrc );  
31
  }
32
33
  result.innerHTML = fragment;
34
})();

Alternative

The method outlined in the screencast is the most readable, however, if you'd prefer a more automated approach, we can apply the values and regular expressions dynamically, like so:

1
2
;(function () {
3
    // simulates AJAX request

4
    var data = [{
5
        title: "Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5",
6
        href: "https://code.tutsplus.com/tutorials/create-a-sticky-note-effect-in-5-easy-steps-with-css3-and-html5--net-13934

7
        imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/771_sticky/sticky_notes.jpg"

8
    }, {
9
        title: "Nettuts+ Quiz #8",
10
        href: "https://code.tutsplus.com/articles/nettuts-quiz-8-abbreviations-darth-sidious-edition--net-23152

11
        imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/989_quiz2jquerybasics/quiz.jpg"

12
    }, {
13
        title: "WordPress Plugin Development Essentials",
14
        href: "https://code.tutsplus.com/tutorials/wordpress-plugin-development-essentials--net-23135

15
        imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/1101_wpPlugins/wpplugincourse.png"

16
    }],
17
        template = document.querySelector('#template').innerHTML,
18
        result = document.querySelector('.result'),
19
        attachTemplateToData;
20
21
22
    // Accepts a template and data. Searches through the

23
    // data, and replaces each key in the template, accordingly.

24
    attachTemplateToData = function(template, data) {
25
        var i = 0,
26
            len = data.length,
27
            fragment = '';
28
29
        // For each item in the object, make the necessary replacement

30
        function replace(obj) {
31
            var t, key, reg;
32
33
            for (key in obj) {
34
                reg = new RegExp('{{' + key + '}}', 'ig');
35
                t = (t || template).replace(reg, obj[key]);
36
            }
37
38
            return t;
39
        }
40
41
        for (; i < len; i++) {
42
            fragment += replace(data[i]);
43
        }
44
45
        return fragment;
46
    };
47
48
    result.innerHTML = attachTemplateToData(template, data);
49
50
})();

This is the method that I'm most likely to use.


Additional Tools

If you'd prefer a more flexible solution, any of the following should do the trick!