JsRender looping, nested objects, and conditional statements.

So far, I’ve posted a couple of very basic introductory posts on JsRender. In this post, I’ll get a little bit more into the meat of the templating language and show looping, conditional statements, and some other bits and pieces.

In the example, I’ve put together a supermarket receipt. It shows the items bought, their quantities and any savings from offers. Here’s the data:

var theReceipt =
  {
    items:
      [
        {
          description:"800g Wholemeal Bread",
          quantity:2,
          price:1.05,
          offer: {qty_needed:2, price:1.90}
        },
        {
          description:"Kellog's Fruit & Nut",
          quantity:1,
          price:2.69
        },
        {
          description:"2 litres Semi-skimmed Milk",
          quantity: 3,
          price:1.18,
          offer: {qty_needed:3, price:3.00}
        },
        {
          description:"1 litre Pineapple Juice",
          quantity:2,
          price:1.10
        }
      ],
      total: 9.79,
      saving: 0.74
  };

The data contains an array of items, each of which contains the the description, quantity, and price of each item. On some items there is also details of any offer. There is also the precomputed total and the saving that the customer has made.

Looping

In the previous post I showed what happens when the object you pass JsRender is an array. But what if the data contains an array as some sub-element? In that case you can use the for tag followed by the name of the array to indicate the start of the loop (and which array to loop over). At the end of the loop repeat the tag but with a slash in front of it (rather like HTML). For the data above, it would look like this:

{{for items}}
  Put repeating template here
{{/for}}

The tags inside the for block will be for current element. So, for the items above, I could use tags such as description, quantity, and so on.

Conditional statements

You can render parts of a template conditionally if you like. You can use the if tag to do that. Again at the end of the block, you put the slash in front of the tag to indicate its end.

{{if some_condition}}
  Put template to render if true here.
{{else some_other_condition}}
  Put template to render here if the second condition is true.
{{else}}
  Put template to render here if previous conditions are false.
{{/if}}

In the example, the test is whether the offer object exists or not. However, it acts just like an if conditional statement works in javascript. So if offer evalates to false, zero, etc. then it will be regarded as false, other values are regarded as true.

{{if offer}}
  <tr>
    <td></td>
    <td><em>{{:offer.qty_needed}} for £{{:offer.price}}</em></td>
    <td><em>save:</em></td>
    <td><em>£{{:offer.price - (quantity * price)}}</em></td>
  </tr>
{{/if}}

Nested object

In the looping section you can access the elements of each item being iterated over. The looping mechanism takes care of that for you, so when you are in the loop each tag is an element of the current item.

You can, as you can see in the conditional statements section above, also see that you can use the standard dot-notation to access nested elements. In this case the elements in the offer object.

Calculations

In the conditional statements section you can see some basic calculations.

{{:offer.price - (quantity * price)}}

The result of the calculation will be rendered to the page.

Rendering options

You will have noticed that templating statements are all in two braces. Where something is rendered the initial opening braces are followed by a colon. This simply outputs the results directly on to the page. This is great if the output is safe (or it is HTML), however if you want to ensure that the output is correctly encoded for a web page you can use a right-cheveron.

  {{:some_html_to_be_rendered}}
  {{>some_text_to_be_escaped}}

The example

The example for this post can be found here. You are encouraged to view the source of the example.

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",
      "thumbnail":"http://farm1.staticflickr.com/1/2843652_f542c664ed_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2843652/in/photostream"
    }, {
      "title":"Forth Bridge",
      "thumbnail":"http://farm1.staticflickr.com/1/2843680_58c5c8003b_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2843680/in/photostream"
    }, {
      "title":"Helmsdale",
      "thumbnail":"http://farm1.staticflickr.com/4/5441773_2929a2ebdf_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/5441773/in/photostream"
    }, {
      "title":"Scottish Parliament",
      "thumbnail":"http://farm1.staticflickr.com/3/6340272_0e7ad78251_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/6340272/in/photostream"
    }, {
      "title":"Space Needle",
      "thumbnail":"http://farm3.staticflickr.com/2013/2410201132_356ff1a147_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2410201132/in/photostream"
    }
  ];

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}}"/>
    </a>
  </div>
</script>

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.

JsRender …. starter for 10

I was going to look at jQuery Templates recently, but then I discovered they have been discontinued. Which is a real pity as I saw a demonstration at a conference about a year ago and they looked rather promising. However, there are other similar projects out there that do similar things. So instead, I’m going to look at JsRender and JsViews.

At the moment there is very little documenation out there for either JsRender or JsViews, so this is some of the bits I’ve been able to piece together. Some of the simpler demos actually only use JsRender. And, of course, at this stage the project is still pre-beta so some of this may change.

To get going you need to add a reference to the JsRender javascript library. You can find that on github. Although you don’t need jQuery for JsRender, it can take advantage of jQuery to make some things easier. I’ll be showing JsRender with jQuery as I happen to think it makes things easier.

Hello World!

To start with the template is rendered in a script block with a type of “text/x-jsrender”. The templated parts themselves are made up of two sets of braces with an expression inside. For example:

<script id="helloTemplate" type="text/x-jsrender">
  <p>Hello, {{:name}}!</p>
</script>

Next, we need some javascript to wire up the template with some data

<script type="text/javascript">
  $(function(){
    // Set up the data
    var thePerson = { name: "Colin" };

    // Render the template to a string
    var renderedHtml = $("#helloTemplate").render(thePerson);

    // insert the rendered template into an existing element
    // In this case it is a span.
    $("#container").html(renderedHtml);
  });
</script>

To see the example in action, click here and view the source of the page to see the underlying code.

Private members in coffeescript and the query string

Because coffeescript is really just a thin veneer over javaScript there are, in my opinion, a few lost opportunities. For example, when you create a class all members (properties or functions) are public. However, there are work arounds.

I created a class to help me work with query string parameters. Actually, I ended up creating two classes, one an implementation class that did most of the hard work, and another to act as the public interface to the rest of the world. The “public” class is attached to the window object to make it globally available within the browser, the implementation class will only be available to other code inthe same script as the script as a whole will be wrapped by the coffeescript compiler in an anonymous function.

The publically available class, the one attached to the window object exposes three functions, yet it doesn’t expose its association to the implementation class. I achieved this by making the the association to the implementation class inside the constructor and then definining all the other functions in the construtor too. Each method I wanted to make public I prefixed with the @ symbole (the equivalent of this. so that it would be available to users of the class

# Define the queryString class, attaching it to the window object,
# effectively making it globally available.
class window.queryString
  constructor: (url) ->
    # The constructor defines a local variable to hold the reference
    # to the implementation class. This acts as a private member variable.
    __qsImpl = new queryStringImpl(url)

    # The public methods are defined on "this" by using the @ prefix
    # They can access the local variables in the parent scope because
    # they are closures.
    @getValue = (key) ->
      result = __qsImpl.params[key]
      if not result?
        result = __qsImpl.canonicalParams[key.toLowerCase()]
      return result

    @count = () ->
      __qsImpl.count

    @hasKey = (key) ->
      return key of __qsImpl.params || key.toLowerCase() of __qsImpl.canonicalParams

The implementation class also detects when the url is null or undefined and automatically finds the url and extracts the query string information for you. With this you can then get access to the query string parameters by using code like this:

# Create the query string object
qs = new queryString()

# Get a value from the query string
theValue = qs.getValue("SomeQueryStringKey")

# Work out if a value is available on the query string
isAvailable = qs.hasKey("SomeQueryStringKey")

# Find the number of query string parameters
numberOfParams = qs.count()

Unit testing with Coffeescript

I’ve recently started  looking at Coffeescript. And to get going with that I’m jumping directly in with unit-testing. I figured that it would be an interesting way to learn the language.

Since coffeescript compiles to javascript, you can use a javascript unit testing framework such as QUnit which can be downloaded from github.

Getting to grips with QUnit

Before we delve into coffeescript part, let’s have a very quick look at QUnit.

In order to run unit tests create an HTML page that will contain the runner. In this page you need to include jQuery, and QUnit (http://code.jquery.com/qunit/git/qunit.css and http://code.jquery.com/qunit/git/qunit.js). The body of your test runner needs to contain elements that QUnit will update during the tests. You also need to include the tests themselves.

I won’t go much further in to QUnit as there is already ample
information about getting going with QUnit over on the jQuery website.

Running coffeescript in the browser

Normally coffeescript is pre-compiled into javascript before being sent to the browser, however it is possible to have the browser compile coffeescript itself. This would not be recommended for production code, but does make life easier for running unit tests as the browser handles the compilation step for you.

You can run coffeescript in the browser by using the script located at http://jashkenas.github.com/coffee-script/extras/coffee-script.js. Then
any subsequent script blocks that are marked with the text/coffeescript type will be compiled on-the-fly. e.g.

<script type="text/coffeescript">
    // Your coffee script code here
</script>

One annoyance I’ve found is that coffeescript relies on “significant whitespace” which means that I’m forced to format my code the way coffeescript likes. In general thats not necessarily a bad thing, especially when you are editing coffeescript files, but with inline script blocks it can be irritating. Your script block may already be indented (and I tend to go for indents of two spaces for HTML files, as opposed to 4 for C#) which coffeescript doesn’t seem to like.

Running some tests

First of all this is what a test looks like in javascript using QUnit.

  <script type="text/javascript">
    $(function(){
        module("My javascript test");

        test("Assert 1 not equal 0", function(){
          ok(1!==0, "One expected to not equal zero");
        });
    });
  &lt/script>

What’s happening above is that the tests run when jQuery is ready. In other words, once the DOM is loaded. (See also: $(document).ready()).

The module method is simply a way of segregating the tests in to groups. All tests that follow a call to module will be grouped into that “module”.

The test happens in the call to test which normally takes a string which is the text to display each time the test is run, and a function containing the actual test. The second test that I have is written in coffee script.

<script type="text/coffeescript">
$(()->
    module("My coffeescript test");
    test("Assert 1 equals 1", ()-> ok(1==1, "One expected to equal one"));
);
</script>

While in coffeescript you don’t need the brackets around the function parameters, I prefer them. Nor do you need the semi-colon to terminate each statment, and again this is personal preference. You’ll see lots of coffeescript that won’t use brackets and semi-colons in the above situations.

Here is the result of the two tests above:

Test 	    runner with passing tests

In both tests above there is a call to ok which asserts that the condition passed in as the first argument is true, if not it fails the test. When a test fails the text in the second parameter of the ok function is displayed. For example, a test designed to deliberately fail:

    test("Assert 2 equals 3", () -> ok(2==3, "2 expected to equal 3"));

And the result in the test runner:

Test runner with failing test

Unit testing with .coffee files

Eli Thompson has an example of how you might want to put together unit tests for a
system written in coffeescript
. The core of his example is to define a list of coffeescript files and a list of tests and have a bit of coffeescript dynamically load them in order to run the tests.

In that example, scriptsToTest contains a list of coffeescript files that contain the code to test, and a list of tests which reference the files that contain the actual tests. The code then loads each coffeescript file, compiles it to javascript and loads it into the DOM so that the browser can execute it. The code that does all the hard work is a rather elegant 9 lines of
coffeescript (not including the declaration of the files involved).

More information

This was a very quick introduction to unit testing with QUnit and
using coffeescript. Here are links to more resources to continue
with: