Easier HTML with Haml and Sinatra

I have been doing professional web development for about 3 years now and HTML tables are still not getting any easier to look at (especially poorly formatted ones).

With modern text editors our markup is mostly written for us and in the case of certain content management systems (CMS) we hardly  need to write any HTML at all anymore.

Nevertheless as a web developer it is almost entirely impossible to forget about writing some markup.

I came across Haml and Sinatra about 2 years ago, through my interest in the Ruby language. Though I cannot say that I’ve gone on to create amazing web apps with these tools yet, I have found myself coming back to Haml again and again to rapidly flesh out some HTML when needed.

Maybe this post should have been called “writing HTML tables sucks” ‘cause that’s really why I find myself switching over to Haml on occasion.

My Sinatra Setup

Required items:

First of all this is a super basic example and more than anything it is just a quick development tool. It’s a tool that gets used often and for that reason it should be completely painless and easy to get to.

Step one: This app needs a home, I use a local directory called ‘Sinatra’.

In there lives one ruby file and two directories each with just one file (the public directory is where you place files such as CSS, Images and Javascript – for this setup it is optional as I only use the app to generate some HTML):

/Sinatra

– app.rb

– /public (optional)

– – style.css (optional)

– /views

– – index.haml

The app is instructed what to display on what page in the app.rb file. The root page is set to display the index.haml view (a view is a template file in Ruby). Once the Sinatra and Haml gems are installed the app.rb is set up something like this:

require 'rubygems'
require 'sinatra'

get '/' do
	haml :index
end

Initialization of the app is done through the command line, first by navigating to the project and then running:

ruby app.rb

If all is good, the command line will say this:

Sinatra/1.4.2 has taken the stage on 4567 for development with backup from Mongrel

Now the app is viewable on http://localhost:4567/

All that’s left to do is write some Haml inside the views/index.haml file. No need to restart the app for changes in views/ or public/ just refresh the browser.

Protip: Because I use this so frequently and I always have a Terminal window (mac command line) open it made sense to create a command alias which will change my current location to the app’s directory. From there I am able to open the app in my text editor and initialize the app as well.

This has helped me a lot in the past and continues to be an useful little tool. Haml is just easier on the eyes and easier to write than HTML in my opinion.

Leave a Reply

Your email address will not be published.