Quick Tip: Create a Makeshift JavaScript Templating Solution
videos

Quick Tip: Create a Makeshift JavaScript Templating Solution

Tutorial Details
    • Difficulty - Intermediate
    • Format - Screencast
    • Length - 7:59

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

<!doctype html public 'ahh hell yeah'>
<html>
<head>
	<meta charset=utf-8>
	<title>Simple Templating</title>
</head>
<body>
  
  <div class="result"></div>
  
  <script type="template" id="template">
    <h2> 
      <a href="{{href}}">
        {{title}} 
      </a>
    </h2>
    <img src="{{imgSrc}}" alt="{{title}}">
  </script>

</body>
</html>

JavaScript

;(function() {
  // simulates AJAX request
  var data = [
    {
      title: "Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5",
      href: "http://net.tutsplus.com/tutorials/html-css-techniques/create-a-sticky-note-effect-in-5-easy-steps-with-css3-and-html5/",
      imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/771_sticky/sticky_notes.jpg"
    },
    {
      title: "Nettuts+ Quiz #8",
      href: "http://net.tutsplus.com/articles/quizzes/nettuts-quiz-8-abbreviations-darth-sidious-edition/",
      imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/989_quiz2jquerybasics/quiz.jpg"
    },
    {
      title: "WordPress Plugin Development Essentials",
      href: "http://net.tutsplus.com/tutorials/wordpress/wordpress-plugin-development-essentials/",
      imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/1101_wpPlugins/wpplugincourse.png"
    }    
  ],
      template = document.querySelector('#template').innerHTML,
      result = document.querySelector('.result'),
      i = 0, len = data.length, 
      fragment = '';
  
  for ( ; i < len; i++ ) {
    fragment += template
      .replace( /\{\{title\}\}/, data[i].title )
      .replace( /\{\{href\}\}/, data[i].href )
      .replace( /\{\{imgSrc\}\}/, data[i].imgSrc );  
  }

  result.innerHTML = fragment;
})();

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:

;(function () {
    // simulates AJAX request
    var data = [{
        title: "Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5",
        href: "http://net.tutsplus.com/tutorials/html-css-techniques/create-a-sticky-note-effect-in-5-easy-steps-with-css3-and-html5/",
        imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/771_sticky/sticky_notes.jpg"
    }, {
        title: "Nettuts+ Quiz #8",
        href: "http://net.tutsplus.com/articles/quizzes/nettuts-quiz-8-abbreviations-darth-sidious-edition/",
        imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/989_quiz2jquerybasics/quiz.jpg"
    }, {
        title: "WordPress Plugin Development Essentials",
        href: "http://net.tutsplus.com/tutorials/wordpress/wordpress-plugin-development-essentials/",
        imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/1101_wpPlugins/wpplugincourse.png"
    }],
        template = document.querySelector('#template').innerHTML,
        result = document.querySelector('.result'),
        attachTemplateToData;
    // Accepts a template and data. Searches through the
    // data, and replaces each key in the template, accordingly.
    attachTemplateToData = function(template, data) {
        var i = 0,
            len = data.length,
            fragment = '';

        // For each item in the object, make the necessary replacement
        function replace(obj) {
            var t, key, reg;

            for (key in obj) {
                reg = new RegExp('{{' + key + '}}', 'ig');
                t = (t || template).replace(reg, obj[key]);
            }

            return t;
        }

        for (; i < len; i++) {
            fragment += replace(data[i]);
        }

        return fragment;
    };

    result.innerHTML = attachTemplateToData(template, data);

})();

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!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://ahermosilla.com Andres Hermosilla
    • http://www.jeffrey-way.com Jeffrey Way
      Author

      That’s definitely cool for smaller templates. But for most things, I’d prefer to use an HTML-based approach.

    • http://smartpapers.tk Mehdi Raza

      WOW! That’s small and efficient.

  • phpman

    nice tut :)

  • phpman

    but when should use this way ?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Any time that you might normally nest a bunch of HTML in your JavaScript. Maybe you’re pulling in a JSON feed, filtering through it, and adding something to the page.

      • Sean Erdrich

        First, I’m still new when it comes to writing javascript, so forgive me if these seem like obvious questions…

        Is this something that would be suitable for, let’s say, blog posts? Or is it an alternate solution for working with lots of HTML that needs to be rendered with Javascript?

        Would it be possible to have it pull the array from a separate file/database that could have new entries added to it through another page or site? (Let’s say a page with a form containing inputs for title, href, and imgSrc that automatically adds the values to the array in a separate file).

        Either way, great tutorial!

        Thanks,

        Sean

      • Sean Erdrich

        Okay, so nevermind about the blog posts….

  • http://www.webmaskine.com/ Pachito Marco Calabrese

    Really interesting solution for small projects! Very nice!

  • http://www.wimbledon-it.co.uk Bjoern

    Thats a nice one. I will also have a look at the jquery template stuff you mentioned. Thanks for that!

    • http://www.benedikt-wolters.de migthyuhu

      thought the same thing, as this is pretty basic

  • Suny

    As you noted in the video, each regex should include the ‘g’ modifier. Your source and the download link source don’t currently reflect that.

    Otherwise, nice, simple, and clear. Thanks!

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      They do now.

  • Ingo Fahrentholz

    Nice!

  • Mario

    Nice!

    But I have to ask, does this affect SEO negatively?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      It’s unrelated to SEO. You of course wouldn’t want to build a blog this way. It’s for when you’re pulling in feeds, making AJAX requests, etc.

      • Tony

        I like this , I did the backbone contact tut and can see where this will come in handy for a project I am thinking about, oh nice redesign of your site Jeff !

  • Clayton

    I understand this is an example. But to make me understand completely what would a real world situation be of using this? How would you collect your data dynamically to display it this way in the function, like from a real feed. With my inexperience with javascript, I dont know how or when to use something like this. Please explain to a beginner such as my self!

    Thanks, Clayton

    • http://rick.com Rick

      It is for forms that demand to be dynamic. See knockout.js.

  • Brad

    I remember the twitter jquery template you made during your justin Beiber phase. I still use that as an example for making templates.Good to revisit this in this manner

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      The Justin Beiber phase hasn’t ended!

  • Johny

    But what i can do if i get hundreds of theese articles i must make hundreds of lanes ….. ?

  • http://dan.cx/ Daniel15

    This is pretty good. I like John Resig’s approach, too. His is a bit different – It takes a template and creates a pure JavaScript function representing the template. Which means that (in theory anyways) using the same template multiple times should be faster than doing the variable interpolation every time.

    http://ejohn.org/blog/javascript-micro-templating/

  • http://www.iamlukasz.com Lukasz

    I would not recommend building a whole that way. Only small parts that don’t depend on SEO.

    I am having to solve an issue at work where all product information is populated using JSON and google cache only shows the header and footer and most of the js inline code is hidden using css.

  • http://www.mediaty.com Martin

    This is pretty good. I like John Resig’s approach, too. thanks

  • http://www.dreu.info Robert-Jan de Dreu

    Hey Jeffrey,

    I was wondering. Why did you choose for making your own template language? We have solutions like mustache now, which is really similar to your template language but also with support for loops etc.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Mustache or Handlebars will be far more flexible. Sometimes, though, you’re working on a simple project or demo and simply need to bind a bit of data to some HTML elements. In those cases, a full templating solution can be overkill.

      But, sure, for larger projects, I’ve always used the jQuery Templating plugin. Now that it’s no longer in development, I’ll probably switch over to Handlebars.js/

  • http://www.visualdecree.co.uk Mat D

    Great tut, i really love how this works. As a newbie to coding, i find this really interesting. BUT can you help me out in understanding when is it good to use things like this? I love this though and i will definately play around with it to learn more.

    Regards
    M

  • http://omarabid.com Abid Omar

    One thing I don’t get is why are you using a “script” tag. Should a div or UL tag be better?

    • Rui

      Seriously?!…

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Abid – we’re creating a template here – not actual markup that the browser should interpret.

  • Sergio Medina

    Nice code,

    Although I would cache the regexp in a js object.

  • http://www.udgwebdev.com Caio Ribeiro Pereira

    Another good javascript template is JQuery Template

    Look this http://www.udgwebdev.com/conhecendo-o-jquery-template/

  • http://www.topz10s.com Amrinder Singh

    Very good example of Jquery Template.

  • http://albino.be Joachim Nijs

    I recently developed a website which is full-blown ajax.
    All the content is delivered as json and to display it, I also needed a js template system with built in logic like “if”, “for each”, …
    I used the official jquery.tmpl() plugin, works very good!
    script: https://github.com/jquery/jquery-tmpl
    docs: http://api.jquery.com/tmpl/

    PS:
    site I’m talking about: http://frieke.com

    • Michael Kennedy

      absolutely beautiful site style Joachim

  • Andej

    Great tutorial, even for such beginners like me))
    Thanks a lot!

  • http://www.yagudaev.com Michael Yagudaev

    The approach outlined here is too long. A much better alternative is to use a small line of code like this:

    template.replace(/{{(.*?)}}/, function(match, variable) { return data[variable]; });

    This is much shorter and cleaner.

    But good tutorial in any case :).

  • http://cawoodm.wordpress.com/ Marc

    Been looking for a micro templating solution for ages and this article really got me thinking! Who wants another external .js when a double loop with replace will do? I’ve adapted your approach as follows:

    function microTemplate(data, temp, el) {
    if (typeof temp.innerHTML==’string’) {el=temp;temp=temp.innerHTML;}
    data = [].concat(data);
    for (var i in data)
    for (var f in data[i])
    temp = temp.replace(new RegExp(‘{{‘+f+’}}’, ‘ig’), data[i][f]);
    if (el && typeof el.innerHTML == ‘string’) el.innerHTML = temp;
    return temp;
    }

    Advantages:
    – More compact (copy+paste into any project)
    – Accepts objects or an array of object
    – Applies the template result to an element’s innerHTML
    – Allows the template to be stored in the element’s innerHTML

    Example:

    My name is {{name}}
    microTemplate({name:’John’, $(‘#op’)[0]):

    Thanks!

  • http://cawoodm.wordpress.com/ Marc

    Been looking for a micro templating solution for ages and this article really got me thinking! Who wants another external .js when a double loop with replace will do? I’ve adapted your approach as follows:

    function microTemplate(data, temp, el) {
    if (typeof temp.innerHTML==’string’) {el=temp;temp=temp.innerHTML;}
    data = [].concat(data);
    for (var i in data)
    for (var f in data[i])
    temp = temp.replace(new RegExp(‘{{‘+f+’}}’, ‘ig’), data[i][f]);
    if (el && typeof el.innerHTML == ‘string’) el.innerHTML = temp;
    return temp;
    }

    Advantages:
    – More compact (copy+paste into any project)
    – Accepts objects or an array of object
    – Applies the template result to an element’s innerHTML
    – Allows the template to be stored in the element’s innerHTML

    Example:

    My name is {{name}}
    microTemplate({name:’John’, $(‘#op’)[0]):

    Thanks!

  • http://www.facebook.com/mittul.chauhan Mittul Chauhan

    so useful indeed .. thanks a lot