Economy of Effort

Twitter LinkedIn GitHub Mail RSS

Convert Html To Haml (And Back Again) Within A Vim Buffer

Haml is great. Haml is the JSON to HTML’s XML: all of the garbage and noise stripped away, with only the data and minimal amount of ceremony left.

I use Haml on all Rails projects now, but when dealing with legacy projects, I still encounter HTML/ERb templates.

Using the html2haml command-line tool, I can easily convert HTML/ERb in my Vim buffer into Haml.

The project distributes as a Ruby gem, so installing is accomplished with:

$ gem install html2haml

Then, the magic is done with some Vim bindings to feed a buffer or visually-selected chunk of text to the application, and paste its output back into the buffer, replacing the original text.

nmap <leader>h :%!html2haml erb 2> /dev/null<CR>:set ft=haml<CR>
vmap <leader>h :!html2haml erb 2> /dev/null<CR>

When changing the entire file, I’ve also added the command to change the filetype in the Vim buffer, for convenience.

That takes us from HTML/ERb to Haml, but what if we need to go back in the other direction? This is possible with the haml2erb tool. Unfortunately, this tool is not actively maintained the way html2haml is. For me, on Ruby 2.1.1, it was necessary to install the 0.3.0 prerelease version, as the last official version would not build. Once installed, though, it worked as expected.

We must explicitly indicate which version to install in order to install prerelease gems:

$ gem install haml2erb -v ‘0.3.0.pre.3’

The Vim bindings are much the same as the html2haml ones:

nmap <leader>e :%!haml2erb 2> /dev/null<CR>:set ft=eruby<CR>
vmap <leader>e :!haml2erb 2> /dev/null<CR>

I have not used this nearly as much as html2haml, as I’m rarely changing layout code from Haml back into HTML. However, the couple of times I have needed to do it, it has worked exactly as expected..