Sinatra, Mustache and Heroku – change of plans

Okay, I really like Mustache, it’s clean, it has a reasonably small set of options (conditionals, lists etc.) and has many implementations. One of them being javascript (Mustache.js).
So, i thought what about using Sinatra to generate JSON responses and serving templates, while the client is responsible for the representation. The benefit being a clean RESTful application and a deferred rendering process allowing to play with different options on caching JSON objects and exploring AJAX features.
And above all a fun project.
So, the basic idea:

  1. the root path “/” reads an index html file and hands it out
  2. navigation elements trigger to asynchronous AJAX requests (one for the template, one for the view)
  3. when both are finished mustache.js kicks in and renders the page (or parts of it)

app.rb

get "/" do
  response = File.open("index.html").read
  "#{response}"
end

index.html

...
var template = null;
var view = null;
var templateFinished = false;
var viewFinished = false;

function getTemplate(template){
  [...] xhRequest [...]
  if(request.readyState == 4){
            template = req.responseText;
            templateFinished = true;
            process();
        }
  }

function getView(view){
  [...] xhRequest [...]
  if(request.readyState == 4){
            view = req.responseText;
            viewFinished = true;
            process();
        }
  }

function process(){
  if(templateFinished == true && viewFinished == true){
	document.getElementById("content").innerHTML = Mustache.to_html(template,view);
    }
    else{
        return;
      }
}

So, in my case the rendered stuff replaces the content in the div with the id “content”. To elaborate on that one could pass the id of the element to be replaced as an option to the function and really play with this.

Leave a Reply

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 )

Google photo

You are commenting using your Google 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