Skip to content

Template Converters ERB to SLIM

Anthony edited this page Sep 12, 2024 · 15 revisions

How to convert your .erb templates to .slim

Currently there are two ways to convert your ERB templates to Slim. One is using the still experimental html2slim gem. The other one is converting to HAML and then to Slim, using the html2haml and haml2slim gems.

Using html2slim

Install the gem.

$ gem install html2slim

Note

For Ruby 3.x projects, it is recommended to install html2slim-ruby3 instead to fix a crash while converting files until the next gem release (source issue).

Now you have two command line utilities html2slim and erb2slim. Just run erb2slim -h and you'll receive more instructions. The current version (0.0.2) will output something like that:

$ erb2slim -h
Usage: erb2slim INPUT_FILENAME_OR_DIRECTORY [OUTPUT_FILENAME_OR_DIRECTORY] [options]
        --trace                      Show a full traceback on error
    -d, --delete                     Delete ERB files
    -h, --help                       Show this message
    -v, --version                    Print version

Here you can see before and after. Slimmer, hum?

Using html2haml and haml2slim

See also: https://coderwall.com/p/bn1akg/erb2slim-convert-erb-to-slim

Install HAML dependencies on your environment or your gemset

$ gem install haml # https://github.com/haml/haml
$ gem install hpricot
$ gem install ruby_parser
$ gem install html2haml

Switch to HAML templating

$ find . -name '*erb' | \
  xargs ruby -e 'ARGV.each { |i| puts "html2haml -r #{i} #{i.sub(/erb$/,"haml")}"}' | \
  bash

Install SLIM tool dependency

$ gem install haml2slim # https://github.com/fredwu/haml2slim

Switch to SLIM templating

$ find . -name '*haml' | \
  xargs ruby -e 'ARGV.each { |i| puts "haml2slim #{i} #{i.sub(/haml$/,"slim")}"}' | \
  bash

Clean ERB and HAML templates

$ find . -type f | egrep "(.erb|.haml)\$" | xargs rm

Remove dependencies

$ gem uninstall haml
$ gem uninstall hpricot
$ gem uninstall ruby_parser
$ gem uninstall html2haml
$ gem uninstall haml2slim

That is all, have fun