Last Updated: February 25, 2016
·
10.38K
· jamesduncombe

erb2slim - Convert ERB to Slim

Converting between ERB and Slim seems to be a pain for some reason. However, I found html2haml and haml2slim and wondered why we can't just convert to Slim in one hit (2 if you include the gems ;). Well, here goes...

Firstly install the following gems:

gem install html2haml haml2slim --no-ri --no-rdoc

Then you can run the following to convert ERB to Slim in place (it creates a Slim file and removes the old ERB file):

find ./app/views -name '*.erb' | xargs -I file sh -c \
'html2haml --erb file | haml2slim > $(echo file | sed 's/erb/slim/') && \
rm file'

Quick breakdown of what's going on:

  • Find all the erb files in the app/views directory (this is tailored for Rails but could be used elsewhere

  • Take that output and line by line pass it off to xargs (read about this, it's badass!). I'm using -I flag here to give myself a reasonable placeholder name for the filename from find.

  • sh -c takes the command within the quotes as a string and evaluates it

  • In there we convert the file to HAML also paying attention to ERB tabs (--erb)

  • We pipe that into haml2slim which takes our HAML and outputs/redirects it to the original file but with a new extension (we're using a subshell $() here and then use the sed command to replace the original .erb with .slim in the filename)

  • Finally, if that works, remove the original - you may want to change this if you want to keep the original erb file around

You could take this command and alias it in your .zshrc file or other shell init script.

Thanks to:
haml2slim,
html2haml
and http://www.22ideastreet.com/blog/2011/10/19/converting-erb-to-slim/ for giving me a few ideas...

3 Responses
Add your response

very good! do you know how to keep empty lines so that code doesn't get all glued?

over 1 year ago ·

This online tool works well too http://erb2slim.herokuapp.com/

over 1 year ago ·