Posterous theme by Cory Watilo

Please save me from myself and Haml (Use haml to render HTML code examples)

Once you write markup in haml, you'll do anything to avoid writing straight HTML ever again. This is an extreme example.

I needed to make a page that shows my tech-savvy users some example HTML and CSS.

So of course I wanted to use haml to render HTML that would then be escaped and whitespace preserved in a <pre> element.

First I read the reference and haml helper docs for ideas. All of these looked promising:

  • &= and ~
  • Combinations of the :plan, :escaped, and :preserve filters. They didn't seem to play together.
  • The #capture_haml, #preserve, and #escape_once haml helpers

.. but I couldn't get them to work in concert.  I unsuccessfully googled the following phrases (and many more) looking for help: haml render html in pre or code, haml plain html filter preserve white space, haml generate escaped html.

The right solution would be to contribute a new filter for haml.  But here is my solution for now:  I read the haml source and found the following to work. I fear it's pretty ugly.

The output, as rendered in a browser:

Media_httpimgskitchcom20090720dki2j7kjayj35si2nr24hrqbk1jpg_ckyaqjxeaexisun

As you can see, it works for Sass as well. Note that %[text across lines] is short hand for the %q{} ruby literals, which is a nice way to code readable multiline strings.  You need to be careful to left align that column of haml or sass (lines 4 and 11) with the preceeding variable definition to achieve proper indentation when parsed.

If you know a cleaner way to achieve this, I'd love to learn from you. I'm a relative newcomer to software development.