Super simple jQuery templating

Working with jQuery, it is common to find yourself needing some kind of templating solution. There are plenty out there, however sometimes the use-case is simple enough that you don’t really need a fully blow templating plugin.

We’ll take a task list as an example (just to be original). Lets say you have the following task objects in an array:


var tasks = [
  { id: 1, name: 'A todo item' },
  { id: 2, name: 'Another todo' }
];

Now you want to display them in an unordered list with checkboxes etc. What I like to do is create a ‘templates’ object, which contains my basic templates:


var templates = {
  taskList: $('<ul class="task-list">'),
  taskItem: $('<li><input type="checkbox" /> <span /></li>')
}

With these templates in place, it’s a simple case of cloning them when required and inserting the relevant data. jQuery’s ‘text‘ and ‘attr‘ methods are ideal for this as they handle the escaping of html entities. Based on this we can iterate over our tasks array and insert the relevant items in the dom:


var list = templates.taskList.clone();
$.each(tasks, function() {
  templates.taskItem.clone()
    .attr('id', this.id)
    .find('span').text(this.name).end();
  list.append();
});

$('body').append(list);

And that’s it, by using jQuery’s ‘text‘ and ‘attr‘ functions, you have complete control over your templates, without having to remember to escape html. Your templates can be stored away in an external javascript file and everyone’s happy.

“Ramble”, the Javascript Cucumber Port (work in progress)

I am a great fan of Cucumber when it comes to integration testing, however testing heavy use of Javascript can be a little tedious.

I have looked into the different solutions out there such as Selenium but found them all to be fiddly to setup, however Capybara helps on this front. I was thinking, what if Cucumber could run in the browser? No need for Javascript adapters or XML parsers, Safari/Chrome/Firefox already do a great job of this. Manipulating the page such as filling in forms, clicking links etc. could all be done with jQuery, in a very concise manor.

I decided to create a proof-of-concept while it was still fresh in my head. This is by no means a fully working release and the code leaves a lot to be desired in it’s current state, however it shows the benefits of a “Cucumber in the browser”. The main benefits I can see so far (for both javascript and non javascript apps) are:

  • Speed – browsers are getting extremely quick at this DOM stuff.
  • Flexibility – everything happens client-side meaning you can easily test with any server technology.
  • Simplicity – no need for complex javascript adapters, XML parsers etc.

The basic file structure is very similar to Cucumber:

  - features
    index.html
    - js
        ramble.js
        jquery-1.4.2.js
      my.feature
    - steps
        web-steps.js
    - support
        paths.js

Step definitions can be defined in plain old javascript files with plain old jQuery, in this case web-steps.js. Currently the step definition are expected to throw an error if they cannot be fulfilled, this may change when a solid API is nailed down:


  // The value of 'this' is the current document as a jQuery object.
  ramble.match(/^I follow "(.+)"$/, function(link_text) {
    var link = this.find('a').filter(function() { return $(this).text() == link_text; });
    if(!link.length) throw("Can't find link: " + link_text);
    link.click();
  });

Scenarios are exactly the same as in Cucumber, so you can do something like the following:

  Scenario: User fill out a form
    Given I am on the homepage
    And I follow "Tell us your name"
    And I fill in "First name" with "Jamie"
    And I fill in "Last name" with "Hill"
    And I press "Submit"
    Then I should see "Thank you for your details."

You can now simply drop the features folder into the public area of your app and visit the url in your browser. You should see the relevant steps go green or red as the app is navigated in an iFrame.

I plan to first tidy up the API (and unit test) and then aid the writing of scenarios by adding the ability to record them within the browser (Selenium style).

I’d like to hear peoples views on this… please don’t be too hard on the code, it’s more of a mind-dump than anything else at this stage (around 100 lines). There is an example of testing a static site included so just load the features/index.html file in your browser to see it run.

http://github.com/soniciq/ramble

Update 04/07/10: As noted by Andrew in the comments, you will need a server running in order for browsers to get access to the pages for testing.

I have added a simple server script allowing the features to be run locally (requires Ruby). If you want to see it in action, just run:

cd /path/to/ramble/checkout
ruby server.rb

…and then visit http://localhost:1234/features in your browser (tested in Firefox, Chrome and Safari). Note that Ramble is not at all dependent on Ruby, it is just used for running a local test server.

Screenshot

Ramble in action

No ‘a:visited’ in Safari 5… jQuery to the rescue?

With the release of Safari 5, it seems that the ‘:visited’ CSS pseudo selector no longer takes affect. I completely understand it being removed due to breadcrumb sniffing but from a user’s perspective, differentiating between links that you have visited and those that you have not is very handy.

jQuery to the rescue

Using jQuery, we can easily add this functionality back in, without the XSS problems associated with the browser handling it.


$('a:not(.visited)').click(function() {
  $(this).addClass('visited');
});

You can then go ahead and set a different style for links that have the ‘visited’ class.

The problem with this approach is that it will only work for links opened in a separate window or tab and not persist when you leave the current page, as all added classes will obviously be removed. There is probably a way to store a list of which links have been visited in a cookie, however each link would need a unique identifier… something for another time.

Update

It seems that the ‘:visited’ selector does work in some cases in Safari 5 but not sure of the circumstances, can anyone shed any light on this?

jQuery Colorbox within “overflow:hidden” container in Webkit

Wow, that’s a mouthful of a title.

Just run into an interesting bug in Webkit I believe. When using Colorbox on a link contained inside a div who’s overflow attribute was set to hidden, the div was being scrolled to the bottom when hitting the “close” link of the colorbox. This only seemed to happen in Webkit browsers.

The solution was to watch for a scroll event on the div in question and scroll back to 0:


$(document).ready(function() {
  var viewer = $('#viewer');
  viewer.scroll(function() { viewer.scrollTop(0); });
});

Obviously, this is only a fix when you require your content to always be scrolled to the top, however this could serve as a starting point for other scenarios.