JsRender and arrays

Previously, I showed how to very quickly get up and running with JsRender witha very simple hello world demonstation. In this post I’ll be extending things a little further showing you how simple arrays of data are handled.

For this demo I have an array of data representing photos from my flickr account. This is what the data looks like:

var thePhotos =
      "title":"Forth Road Bridge",
    }, {
      "title":"Forth Bridge",
    }, {
    }, {
      "title":"Scottish Parliament",
    }, {
      "title":"Space Needle",

The template defines how to render a single element in the array. There is also a special token available {{:#index}} which allows you to get the index value into the template. In the example below, I’m adding one to it in order to put a sensible number next to the photo.

As you can also see, you can place template placeholders in many places, includeing inside attributes in HTML elements.

The template looks like this:

<script id="photosTemplate" type="text/x-jsrender">
  <div class="photoFrame">
    <span class="index">{{:#index+1}}</span>
    <a class="photoLink" href="{{:url}}">
      <span class="photoTitle">{{:title}}</span>
      <img class="photo" src="{{:thumbnail}}" alt="{{:title}}"/>

The code to render the template and add it to the page is pretty much the same as last time.

I’ve also put together a full example to look at, feel free to look at the source of this page.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s