Templating is an important part of working with JavaScript applications. It's fairly common that data is available to you, but not in a format that is ready display on screen. That is commonly (but not always) data in the JSON format. That's a great format for working with in JavaScript, but we still need to format it into something we can use.

For instance, here's some fictional data we might have on hand:

var data = {
  movies: [
    {
      movieTitle: "Ender's Game",
      movieDirector: "Gavin Hood",
      movieImage: "http://s3-us-west-2.amazonaws.com/s.cdpn.io/3/movie-endersgame.jpg"
    },
    ...
  ]
}

And ultimately we'd like to make that into:

<div class="module module-movie" style="background-image: url(http://s3-us-west-2.amazonaws.com/s.cdpn.io/3/movie-endersgame.jpg);">
  <div class="movie-info">
   <h3 class="movie-title">Ender's Game</h3>
   <p class="movie-director">Gavin Hood</p>
  </div>
</div>

You might think jQuery is awesome at that. jQuery is full of DOM traversing/manipulation tools. But it doesn't have a very robust set of DOM creation tools you might say. I believe the jQuery team was considering adding templating at some point, and even toyed with an "official" plugin, but it didn't take off.

In this video we just don't do what today is traditionally thought of as templating. We just straight up build a new <div> with jQuery and use string concatenation to build the HTML we need and ultimately inject it onto the page. There is nothing technically incorrect about that, but I try and drive home how this approach can get quickly out of hand.

In just the little bit of JS we write in this video, we're mixing a variety of concerns/jobs:

  1. Getting the data. We just have it on hand here, but likely this is a bit more complex. Perhaps an async Ajax request with error handling and caching and such.
  2. Display logic. Deciding what we need to show. How many? Which parts? Based on what?
  3. Event handling. Our newly-injected divs had event handling added as we created them, rather than delegating.
  4. Templating. The HTML that we create to accomplish the design, structure the data, and accommodate or needs.

This is the spaghetti-ish code we finished up with:

See the Pen 31b07f30dce13b31904da36693b29b41 by Chris Coyier (@chriscoyier) on CodePen

The next block of videos is going to focus a bunch on templating because that's super important, but ultimately we'll be sort of breaking apart all these concerns and ending up with much more organized and maintainable code.

Comments

  1. User Avatar
    Austin Peterson
    Permalink to comment#

    How could I use json to create a list of links, then use those links to bring in the data stored in the same json file and format that as page that’s loaded in without reloading?

    $.getJSON('products.json', function(data) {
        console.log(data.category.stemcells.length);
        var i;
    
        for (i = 0; i &lt; data.category.stemcells.length; i++) {
      $("", {
        html: "<a href='" + data.category.stemcells[i].link + "' rel="nofollow">" + data.category.stemcells[i].name + "</a>"
        }).appendTo("#movies");
    }
    
    });
    
    • User Avatar
      Chris Coyier
      Permalink to comment#

      I’m having trouble understanding what you need. Sounds like you are on the right track though looping through the JSON. Feel free to re-explain or make a Pen demonstrating the problem people can see.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag