Why use HAML (and SASS)? I already know HTML.

Posted: 2nd February 2010 by M. E. Patterson in Coding
Tags: , , ,

The title of the post is more-or-less a verbatim quote from a coworker, as well as from an unrelated colleague of mine from a previous job. I was asked that question and, to be honest, I was a little thrown both times. I didn’t actually know why I use HAML.  I guess I’d never really considered it much after I started doing everything with it.  It just seemed better and more fun.

So I spent all last night thinking about the answer.  Why use HAML?  For that matter, why use SASS either?  It’s notable, I guess, that yesterday Chris Eppstein was polling his twitter followers on whether they wanted to break SASS and HAML apart to be separate gems … clearly others out there are using one but not the other.

And I suppose it’s not enough to answer that I use HAML and SASS because other luminaries in the Ruby world swear by it.  As my Mom was fond of saying, “If all the other kids jumped off a cliff…”  So I guess that’s not entirely a valid reason.

So, here’s my attempt to coalesce my various reasons for using HAML (and SASS) into a single post, and to try and convince you why I think it’s a great idea.  And to throw a bone to Eppstein, I’ll try to make a case for why, though I have no problem with them being split into separate gems, I still believe they should always go together, just like peanut butter and grape jam.


So this is the obvious one.  Check out the two chunks of code below:

ERB (525 characters; 24 lines)

<% if @users.empty? %>
  <div class="empty_collection">
    <em>Could not find any users.</em>
<% else %>
  <table class="users_list">
      <% @users.each do |user| %>
        <tr class="<%= cycle('odd','even') %>">
          <td><%= user.name %></td>
          <td><%= user.email %></td>
          <td><%= user.age %></td>
      <% end %>
<% end %>

HAML (331 characters; 16 lines)

- if @users.empty?
    %em Could not find any users
- else
        %th Name
        %th Email
        %th Age
      - @users.each do |user|
        %tr{:class => cycle('odd','even')}
          %td= user.name
          %td= user.email
          %td= user.age

Just in terms of key presses, you’re hitting the keys 37% less in this case if you use HAML. In terms of lines of code, you’re getting a 33% reduction. (Hell, WordPress doesn’t even need to display a scrollbar for the HAML example). I don’t know about you, but to me that’s a significant win right there. Every second I spend typing monotonous stuff is a second I didn’t spend building a feature. And when you’re writing hundreds of lines of code in a day, that can add up to a lot of extra time to either drink beer or add extra polish to the feature you’re implementing.


That’s just a fancy way of saying “my brain has to switch gears too much or too drastically, reducing its efficiency.” Anyone who has done significant amounts of HTML and CSS can tell you that the constant back-and-forth between the stylesheets and the html templates becomes something of a rhythm, a development pulse of sorts. But with that rhythm comes delay and context shifts.

In HTML, I type:

<div class="highlight">
  this is some stuff

In CSS, to style this, I type:

.highlight {
  border: 1px solid #f00 }

For those of us well-versed in modern web development, that shift isn’t tough, but it’s still a shift.

Using HAML:

  this is some stuff

That alone improves the contextual parity some, even if you don’t use SASS and just use straight CSS. You type “.highlight” to make the div. You type “.highlight” to style it. Simple.

If you use SASS, it gets even better:

  border: 1px solid #f00

Now, you don’t even have to worry about the curlies (which don’t exist in HTML, causing cognitive dissonance). In fact, the “code” in both the HAML and SASS templates is nearly identical in structure. The only difference is that in the former, you provide the data to display, and in the latter, you provide the presentation styling for that data. If you buy the whole concept behind “separation of concerns” (and you should!), this makes life clean and satisfying.


If you’ve spent as much time as I have looking at someone else’s legacy code in massive enterprise apps, you know how painful it can be to jump in at first. What the hell does this construct even do? Why did they implement this? Why did someone write 6 lines of code that duplicate a function that Ruby/PHP/Java/whatever already has? What are all these non-standard method calls and where do the actual methods live?

This path of fiery hoops must be jumped through before you can really get down to a level of comfort with the code. And you need that comfort to reach your full development speed when implementing or refactoring in that part of the app. The faster you can get there, the sooner you’ll be able to demonstrate your value to the team and to the product.

The bane of my existence has been so-called “cowboy coders,” those individuals who feel it necessary to hack together fast, poorly-considered implementations in order to move on to the next thing and prove to their superiors how “awesome” they are, because they can knock out 10 new features a day. Nice. Good for you, buddy. But you’re costing me, and your team, and therefore yourself, even more time in the long run, with your mistakes, poor architecture that becomes “too big to remove” (hmm…where have I heard that before?), and a product that becomes shackled to the cowboy, who is the only one who understands the parts of the app they wrote. And God forbid if they ever leave the team…

HAML/SASS provide a buffer against the cowboy.

Forcing Harassing Coercing your teammates to use HAML (and SASS) reduces the cognitive complexity of the presentation layer (aka the ‘view’ for you MVC folk), both in terms of number of lines and characters your brain has to process, and in terms of its immediate understandability. And that makes you faster, and your team faster, and your teammates faster. Faster means more features with more polish sooner in the release cycle, with less bugs. And the reduced complexity has the additional benefit of helping to prevent future bugs, because it’s more obvious what’s going on in a particular template. Think of it as the programming equivalent of Scotchgard sprayed on your templates; it might not prevent every stain, but it helps you get the carpet clean quicker.

Sure, the cowboy might still plow through poorly thought-out code (that’s a problem for another day), but at least now it’s easier to understand WHAT he’s doing with 200 lines of business logic jammed into the view. And it’s easier to see why it should be refactored immediately!


At the risk of igniting some holy war about what actually constitutes best practices in the various spheres of HTML, CSS, Ruby, Rails, etc, I think it’s worth discussing the concept of “best practices.” I think adopting Best Practices has gotten a bad rap in the eyes of some developers, especially those for whom learning the latest and greatest tech in the community seems like “following a fad.” Sometimes, the latest and greatest is actually better, because people in the community are actively thinking about better ways to do the things we do every day. Don’t dismiss it out of hand because you’re defending your little island of knowledge. Any time you hear yourself saying, “I already know how to do this. Why should I learn something else?” … stop! Pause and consider your own motivations. There’s a chance you’re dismissing the new tech because you feel threatened by it. Embrace change, people! Embrace new ideas! Try new things! It will make you (A) more educated in your field and (B) more marketable, which gets you (C) better pay and more responsibility. This is a much better and more-fulfilling path to job security than defending your turf and digging in your heels while the programming community moves on past you.

So, that said, I think HAML provides a major advantage here, as well. It’s established best practice that presentation templates (whether in Rails, or Django, or home-brew MVC-based architectures) should not contain business logic or even much in the way of presentational logic. HAML does a great job of gently encouraging you to avoid this problem:

This bit of ruby code is straightforward in HAML and, I would argue, reasonable in the view:

- @users.each do |user|

But in ERB, you’ll sometimes see things like this:

@users.each do |user|
  full_name = user.first_name + ' ' + user.last_name
  savings = sprintf("%.2f", user.savings)
  if savings == 0.0
    savings = false
    savings_row_class = 'red'

While you could do all that in HAML, the inability to break stuff across multiple lines without starting a new hyphen-fronted line makes it feel icky somehow. So then it gently encourages you to break up that code into the model and/or helper methods, where it should have been in the first place.

I’m not saying that HAML and SASS are silver bullets that make you or your teammates code better, but it sure helps. And when someone you know starts bitching about not being able to break a HAML ruby line into multiple lines, you’re probably safe in assuming that they are on the path to doing something Naughty™


So there you have it. There are many other reasons to use HAML and SASS that I’m sure I didn’t cover here. The “fun-ness” of it, the beauty of the syntax, the ability to have it render templates in different formatting modes depending on production or development environments, etc. But hopefully this gives you some food for thought on why I use it, and why maybe you should give it a look (or a second look, maybe?)

  1. David Pardy says:

    When I first saw HAML, I thought it was brutal. Stuck to erb and am now on a proj where they have a boner for HAML. Hated it for one week.

    Now I will never go back to erb (well, some instances where it’s necc in the app but…)

    HAML kicks ass.

  2. Dave says:

    Actually, I take a lot of my last post back. I haven’t done web development in quite a while (have been spending the past few years on the desktop), and was just looking at a page one of our web designers whipped up. The simplicity of the actual HTML is impressive, since all the display logic has been moved to CSS; I do not think any designer would have a problem using HAML for that part. Since so little work is done in the HTML proper, they could use standard CSS with their tools to create the whole page (or SASS, though again I would rather them be able to use whatever tools make them the most productive, and frankly the difference between CSS and Sass seems pretty small).

  3. Dave says:

    As a few people have expressed, my main concern is that if I have a web designer who writes in HTML, and has tons of tools to edit/preview/etc, HAML is a huge problem, whereas with ERB I can at least replace the dynamic bits with code. Yes, I understand some feel that if your designer cannot handle HAML, then get a new one because she is no good, but one could respond that if your developers cannot write wonderful code without ROR as a crutch, go out and get a great C developer. You have who you have, and hiring the best talent at a reasonable cost is not trivial.

    And frankly, I just think it is better practice to have templates for various technologies as similar as possible, and the best way to do that is to have actual standard HTML in them. Imagine if each programming language/framework had an entirely separate language to communicate with the DB, instead of using SQL, for example.

    All that being said, aren’t there any desktop web design tools that work with either ERB or HAML, allowing you to use dummy data during design time?

    • M. E. Patterson says:

      I certainly don’t disagree with any of the points folks have made re: going to war with the army you’ve got.

      The point of this blog wasn’t to say, “You must use HAML or you’re stupid” or “HAML is the way of the future, and all you luddites are going to burn in a fire!”

      The point of the blog was to discuss comments I had encountered from others doubting the value of _learning_ and _using_ HAML. Certainly, if you or your team is happy using your current tools and you’re effective and profitable, there may be little to be gained from changing up your process.

      But that said, there’s GREAT value in having/hiring designers that can do more than edit HTML in Dreamweaver. There’s great value in hiring developers who have enough chops to contribute to more than just the backend of the app, too. And there’s enormous benefit FOR THE DEVELOPER/DESIGNER to learn new skills. A designer who has only ever done straight HTML work in Dreamweaver is imminently less flexible in their career options than a “front-end developer” who can hand-code HTML in a text editor, work inside ERB templates, work inside HAML templates, write jQuery, do both straight CSS and SCSS/SASS, etc. I say this because I always hire the latter before I hire the former, if I can help it.

      Business owners and team managers tend to assume that my blog posts are only directed at them, but I’m also speaking to the individual developer/designer with this post. If you have an awesome career getting paid well to do only HTML with no templating knowledge, then kudos to you! Keep stacking those bills! But if you lose your job, I’d argue that a lot of companies will pass you by if they can get someone with a broader skill set that can contribute to more aspects of their project/site. Doesn’t mean you’re unemployable, but it certainly limits your options. (when I knew only PHP, I could only get jobs at PHP companies. Now I know lots of languages and I can get jobs at lots more companies)

      My post is an argument that you shouldn’t ignore HAML just because it seems like an arbitrarily-different way of writing HTML that you already know. As a snarky aside, I’d recommend you also read books about subjects you’re not familiar with, try foods you’ve never tried before, and go places you’ve never been. Try it, and if it doesn’t make you more effective or you don’t enjoy working with it, then don’t use it.

      As for ‘desktop web design tools,’ I don’t ever use the WYSIWYG sort. But I know that Aptana Studio can handle HAML and SASS. And I believe Coda has third-party plugins for supporting them as well. Dreamweaver might have some plugins for those, too, but I’ve never found good ones.

  4. Tom Wardrop says:

    I’ve been using ERB since I came to the Ruby world around mid-2010. I’ve always been opposed to abstraction unless the benefits are significant, and the drawbacks are minimal.The biggest problem with abstraction is that it normally wastes the domain-specific knowledge you already have. A classic case is with many ORM’s. I already know how to solve my problem in SQL (as does every other developer), why do I and other developers who may have to read and write this code, have to learn a new language to achieve the same result.

    HAML certainly has it’s benefits, and it’s abstraction isn’t that unfamiliar to those use to HTML and CSS. It’s pretty quick to pick-up. My biggest problem however is the inevitable switching between HTML and HAML. Debugging something in the browser for example, I see the HTML. If I then want to bring up the source HAML file for that HTML, I need to do more mental mapping of what I’ve seen in the browser, to the what I’m seeing in my code editor. Another problem is that I often whip up my concepts and designs in plain HTML and CSS, before I even go near Ruby. It’s always been a simple matter of copy and paste the HTML, and then substitute any dummy data with actual dynamic data (e.g ).

    I fear that with HAML, the time I may save in writing HAML will be lost by the initial conversion from HTML to HAML. It is also another thing to learn for developers that wish to collaborate with you. It’s for this reason I’m not sold on HAML. I’m going to stick with ERB for now I think.

  5. copse says:

    Not went through the whole post’s comments, but hey… Forced-indentation › clean source code rendering.
    Why should it remain messy ? IE6/7 feelings while reading in this article.

  6. I’ve been using html and xhtml for the past 15 years, It’s second nature, so when I saw haml I just thought, I don’t need a layer of abstraction on something so simple, there’s no need.

    Having forced myself to give it a go for a couple of weeks though I now find myself hugely reluctant to go back. Its quicker to type, the semantic indentation that used to make me so cross now feels so obvious, it’s easier to read, easier to isolate sections of code and move them about and the output is superb, perfect indentation that you don’t get with ERB.

    You can also mix it with ERB so you don’t have to do a whole project at once.

    • I want to echo this sentiment. I’ve been very skeptical of HAML and SASS because of how familiar I am with XHTML & CSS, particularly because I have worked deeply with an XML-based content management service and so I am also very well versed in XSLT. So, the markup “noise” never bothered me.

      What’s really won me over to trying out HAML & SASS is the idea of cutting out the context shifting. Reducing the barrier between my markup structure and the styles for that markup is really attractive. Thanks for putting down your thoughts on these tools.

    • Same here. I just started using HAML/SASS for a new project. I had resisted for a long time because I really had my workflow dialed in with HTML and I didn’t feel HAML was a big enough win.

      The catalyst in my case was switching to vim and not having a great set of HTML editing plugins yet. With HAML, vanilla vi editing is terrifically efficient. For SASS the wins are more obvious, but at the same time, modern CSS3 with its browser-specific attributes requirement compounds the value.

  7. [...] Why use HAML (and SASS)? I already know HTML. [...]

  8. Pandafo says:

    border: 1px solid #f00

    should be:

    :border 1px solid #f00


    • Pandafo says:

      sorry, disregard my previous comment

      • M. E. Patterson says:

        in fact, in Sass 3.0, apparently you will even be able to do things like:

        .highlight {
          border: 1px solid #f00;
          .span {
            font-size: bold;

        so it’s kinda ordinary CSS, but it can do magical things, like nesting.

  9. [...] Why use HAML (and SASS)? I already know HTML. [...]

  10. Great Read! Looking forward to more! Bookmarked the site and will be back again! :)

  11. M. E. Patterson says:

    As an aside, before someone starts the inevitable rant about production woes, or incompatibility with capistrano/asset_packager/heroku/whatever, there’s a pretty simple solution: generate your CSS from SASS before you deploy, or use capistrano to generate the CSS on the production server before it goes through asset packaging:


  12. Late one night, I switched an entire project from ERB to HAML. At first, I thought it was great, for all the reasons you specified. But then, as the project kept getting bigger and bigger, the HAML code started to get more difficult to deal with.

    The indentation thing is a big deal. I find that it makes the files so fragile. Copying and pasting becomes impossible. You find yourself always worrying about what column something is in. When editing HAML, you need to parse HAML in your head. It basically got to the point where no one wanted to change the HAML templates because they were so fragile. While ERB might take more characters, text editors can still figure out how to indent them. Copy and paste works without a problem. And, as Marc Hedlund already wrote, it’s much easier for the non-programmers to look at and use an ERB file.

    And there’s also something about removing all HTML from your templates that I didn’t like. With ERB, it is easy to spot the dynamic portions of a page. With HAML, it all looks like code, so it all looks dynamic.

    As a result of all of this, we just switched back to ERB (which is an incredible pain, BTW. Converting templates from ERB to HAML was pretty easy, but doing the reverse was no fun at all…)

    As far as SASS is concerned, we had a similar set of reactions. At first it was great to finally use variables for colors, but after a while, the sass files started to look ugly with weird inheritance indentations, etc. We switched to using “less” (lesscss.org), and couldn’t be happier with it.

    Of course a lot of this is a matter of taste, but when it came down to it, we preferred writing HTML and CSS and using technologies that augmented those instead of replacing them with new languages.

    • John says:


      If you’ve ever used haml for a large project or with big template files, you’ll discover that it is very fragile, not just because of indentation, though that’s an issue, but because you’re one level away from your templates, so that’s another layer of abstraction to keep in everyone’s head. For the same reason I avoid builder templates, because erb is far closer to the final output, and after a while the added abstraction of builder syntax just starts to get in the way. In addition, using haml and thus more ruby in templates just encourages you to put more code in the template, which is never a good idea. If your erb is full of garbage code, fix it – your templates should be mostly html, not code.

      If you don’t work with other people it’s fine to use HAML, and good luck to you, but don’t claim it’s the one true way, as this really comes down to preference. Trying to convert a project which has several contributors and/or designers etc involved is a waste of everyone’s time, unless everyone is agreed from the start that it’s a great idea.

      • M. E. Patterson says:

        Honestly, I’ve not found it terribly fragile (not really even sure what you mean by that; how is it any more ‘fragile’ than ERB or Erubis?), and I’ve used Haml in several moderate-sized teams building enterprise software, and it was a breeze. But if you’re concerned about the need for perfect indentation and/or rendering speed, check out Slim. I’ve started moving lots of stuff to Slim and like it very much. It’s less strict than Haml in terms of indents and handles a lot of inlined alternate formats, when you need a block of Erb or Markdown or whatever.

  13. grimen says:

    I’m not religious (except that I think Matz is some kind of god), but…this is worth an: AMEN! Everytime I get the argument that HAML is uglier and less readable than HTML, then I can’t really respect that inside me. After studying psychology and cognitive psychology in university I ask: Explain how a syntax like HTML can be prefered by a brain to a cognitive psychologist; HAML is reducing the noise to a focking tree (like the DOM tree we end up with and want to style and interact with using css and javascript). A tree is one of the most primitively rooted structures we got in our brains – it’s a fractal. In my head I think of .NET developers I’ve met in general (I’ve been one =P), or more explicit: This dude is afraid of a paradigm change – to something more long term – because that might turn what he/she is good at – and spent years learning – is getting less important. Not sure if that is what is happening, but that’s my generalization from my experiences around “new paradigms” i the history in any layer of the soceity as well. What I didn’t expect was to actualy see this behaviour popping up in Ruby community, which is known to be the edgy/crazy developer types. I scares me a bit actually… Good thing technologies like these is gaining popularity, i hope it continues for everyones best. ERB feels like a PHP-plugin into Rails. One of the few things I actually can complain about in Rails; ERB is a bad default.

    • > Everytime I get the argument that HAML is uglier and less readable than HTML, then I can’t really respect that inside me.

      I do respect people that find HAML uglier than HTML, because I know amazingly talended developers that just can’t read Ruby (for instance) at all, despite being extremely skilled and open-minded.

      The same applies to HAML, or Ruby vs Python, etc…

      In the end it’s matter of taste and freedom to choose.

  14. [...] Why use HAML (and SASS)? I already know HTML [...]

  15. M. E. Patterson says:

    All true points. The whitespace thing was the one major concern I had when I started trying it. But I gave it a chance, and I’m not going back. Frankly, I’ve seen just as much HTML written where someone forgot to close a </div> in a big, complicated document and no one noticed for ages until a new version of IE came out that started barfing because of it. At least, with HAML, you get a nice friendly error message if you screw up your indentation. And if you just get slightly out of wack, but it’s still valid enough to render, it’s usually pretty obvious that you did something wrong, and easy enough to fix.

    And I’ll reiterate the commonly-held view that, if you are writing a HAML template so complicated that you’re getting lost in the indentation, you probably should slow down and figure out why your template is so complicated in the first place… :)

    • M. E. Patterson says:

      and you know, if the Python guys can write entire, professional pieces of software with indentation-sensitive code, i think we can handle some haml templates. :P

    • firecall says:

      Frankly, I’ve seen just as much HTML written where someone forgot to close a in a big, complicated document and no one noticed for ages until a new version of IE came out that started barfing because of it

      Just run it through a validator before you deploy! Get the web-dev toolbar in FireFox and it’ll tell you if you have errors right there and then.

      HAML isnt better better because it compiles and spits out errors – you just need to do the same with xhtml.

  16. Rodrigo DeJuana says:

    I’ll start by saying that the only experience I have with haml and sass, is what you showed me in the examples and the stuff I have run across at work, that you have put in (fyi, M. E. Patterson work together).

    I love the idea of sass as a way to add some programmatic abilities to css. At a minimum, I love that I could define a variable and use it over and over again. For example, link_color = #325465.

    HAML on the other hand. I bought buy the I can write it in less lines arguement. Less is not always better. The fact that whitespace has value would end up biting me the ass. I like being able to declare the end of a block with an end or a }. And not have to worry that I forgot to hit a tab or a space. I have been bitten enough by the “if (something) do_something” bugs that I use “if (something) {do_something}” all the time now.

    If the argument for less code is better, lets just right everything in regex.

  17. A note about splitting up Haml and Sass: the purpose of this would be to allow Sass to be more easily used by a non-Ruby audience.

    • M. E. Patterson says:

      I think that’s a great benefit of splitting them up. I just hope (and part of the point of my article was to suggest) that people give both a significant chance before writing off one or the other. I know both have changed the way I even approach app construction. Otherwise I wouldn’t be spending so much time talking about it.

  18. Interesting that you left out guaranteed well-formedness and testability improvements. That stuff jumps to mind as solid benefits even though I’m still very much on the fence about HAML/SASS.

    There’s definitely a stronger argument against these technologies beyond “everyone knows it” or “all the tools support it”. My stance is that all else being equal less code and fewer layers is better. At worst HAML and SASS add another layer of indirection that increases the mental overhead and can be a source of bugs. I realize that they do provide some very useful features, but given that we are already using a backend to generate the HTML, I question whether the improvements are worth it. Given my 10 years experience with CSS and 16 with HTML, I’m probably a bit more wary about things like whitespace bugs than I need to be, but it makes me wonder, what factilities does HAML give you to control whitespace (if you think this is just Netscape 4 stuff, check out the current version of the PS3 browser).

    Anyway, I haven’t made up my mind yet, I still need to try HAML/SASS on a large project, but those are my doubts.

  19. For designers who are averse to code (but still can handle erb) I think HAML offers the following benefits:
    - guaranteed well-formed HTML
    - less visual noise
    - the quicker debugging that happens when you have the above two items
    Also, the designers I’ve shown the following to seem to love it:

    which yields <td class='product' id='product_123'>
    That makes putting css hooks everywhere very easy compared to:
    <td class='product' id='product_<%= @my_product.id %>'>
    Not to mention how much easier it becomes when Products become Widgets - no search and replace.
  20. Marc Hedlund says:

    Won’t someone please think of the designers! *sob*

    No, seriously, a great summary of the case for HAML. I do think the “Forcing Harassing Coercing your teammates to use HAML” line is telling, though. I’ve watched several different people try to bring HAML in at our company and each time hit a barrier of confusion with the non-developers.

    I don’t think for a minute that the designers aren’t smart enough or code-y enough or whatever enough to get HAML and SASS. They are; they got HTML and CSS, which are in many ways as intricate. I think, though, that some of them look on the request for these tools as if the designers started asking the coders to write code in Illustrator. “But your code will look so much more lovely!” they’d say, “Those monospaced fonts are simply unbearable!” and we’d look at them like they were crazy.

    For better or worse HTML is the common ground for many different groups working on a web app. Templating languages like ERB already pollute that common ground and make it more the realm of developers than not. HAML positively annexes that territory, burns its existing structures to the ground, and leaves some of its former residents homeless.

    The benefits you list above are real and are compelling. I wish they came in a package that was more hospitable to non-programmers.

    I wrote about this in 2002 — http://www.oreillynet.com/onjava/blog/2002/12/why_jsp_sucks_so_hard.html — regarding JSP. I’ve seen a number of attempts at what I was looking for show up in the time since, most recently Mustache: http://github.com/defunkt/mustache I would still love to see a clean templating language that could pass an XHTML validator and still be effective, and have support in the frameworks I use like Rails and Tornado. For whatever reason that hasn’t happened at a large scale yet, at least not that I’m aware of.

    • M. E. Patterson says:

      It’s funny, Marc. I actually came up through the ranks first as a designer and *then* as a programmer. For the first few years of my career, just out of college with an English degree and Digital Art minor, I did nothing but static HTML pages and photoshop, photoshop, photoshop. Never wrote a line of code.

      Then I discovered ColdFusion and PHP and was appalled. “How dare they pollute the document structure of HTML so!”

      I’ve noticed that the debate over templating languages tends to boil down to “You should just use raw HTML because everyone can do it.” But the problem is that you inevitably can’t build great APPS unless you have a solid team from the design side all the way thru the code side. And in today’s javascript-heavy, fanciness-heavy apps, even more so. As a result, we start using scripting, which means ERB templates or JSP or large spaghetti chunks of PHP or whatever.

      It’s probably controversial of me, but having worked at an digital marketing agency myself, I say, “If you can’t learn the basics of at least the front-end templating system your app is using, you shouldn’t be coding it. Be happy with your role making photoshop/illustrator mockups and let your company hire some front-end UI/UX developers who are pros at translating your designs to the app templating system. Or… learn to do those things and advance your career. I did, and I’m a moron. You can too.” :)

      That said, the line you pulled out of my post actually comes more from my experience with *developers*, not designers. The pure HTML/CSS designers I know, for the most part, really dig the idea of learning HAML and SASS, and I’ve gotten several of them into using various static website generators so they build in HAML/SASS and then dump to HTML when they’re ready to launch or deliver the static content for a client. It’s actually the career programmers that I’ve seen more pushback from… but those I’ve convinced almost always end up telling me later that they never use ERB anymore…

      • Marc Hedlund says:

        Heh. You may well be right; I’ve gotten that kind of response when I’ve made this argument before. Some people think I’m defending what’s right and good; others think I’m being condescending to the people who aren’t programmers and that I should have higher expectations. I don’t know which camp is right; my gut says that keeping code out of templates is still the right approach.

        There are plenty of reasons (and arguments in my 2002 post) to keep code out of templates beyond just making it easier on non-developers or intransigent developers, though. There’s a reason we have external CSS files and a reason we have unobtrusive Javascript, and I think the arguments I’m making have all the same benefits, regardless of who makes or edits those templates.

        Also, tight binding between the presentation of the app and *any* particular language makes it far more likely that app will never run in anything but its initial language. How many ColdFusion sites are still running today? Is that a good choice? My argument is that language-independent templates (which is one of the goals of Mustache) would make it at least somewhat more possible to migrate off of bad platform choices in a piecemeal fashion.

        So I see your point about any web app developer needing a range of skills and of course I wouldn’t disagree; but that on its own doesn’t convince me that HAML is the way to go. Maybe it’s better to just see the template as nothing but another class in the compiler, and if so, HAML might be a good choice. But I have yet to be convinced that that’s a necessary step.

        • M. E. Patterson says:

          Great point. Ultimately, my argument is more about using haml vs erb with tons of garbage code in it. In that case, I posit that haml wins no problem. Once you get into designers vs developers and language agnostic templates, things get different. Esp. if you’re just making static sites. But then, do we need that template we wrote for a ruby app 4 years ago to be agnostic enough that it can port seamlessly into a erlang app today. I’m guessing no. We’ll prob rewrite that app anyway. So I’d rather have templates now that are readable and clean that will remain so for debugging later.

          • Marc Hedlund says:

            Yup, I can definitely see that point of view.

            I’m working on a HAML project now, though I just started on it. I’ll be interested to see how it goes.

            Thanks for the great post and responses.

  21. [...] more here:  Why use HAML (and SASS)? I already know HTML. « me, Patterson Tags: dismissing-the-new, feel-threatened, hear-yourself, know-how, learn-something, new-tech, [...]

  22. Sigi says:

    This is a reasonable article, however I have a few remarks:

    You are misusing the term “cognitive dissonance”. What it means is to have conflicting ideas about the self, and its (i.e. your) relation to the world in your head at the same time. Simply having to deal with two equally awkward languages (namely CSS and HTML) at the same time does not lead to cognitive dissonance in the actual sense of the word.
    The name for that is “pain in the *ss”.

    What should also be mentioned is that the savings are not in saving on keystrokes, but in reducing the huge burden having to friggin’ READ it. After having worked exclusively with HAML for a while now, all the example code in blogs, which is usually ERB/HTML based is making by brain hurt. It just doesn’t make sense to write literal HTML. The format sucks.

    The BIG MYSTERY is why not everybody is using HAML exclusively. The benefits are obvious and the drawbacks (over HTML-based templating) non-existent, as long as you’ve got a solid HAML engine.

    • M. E. Patterson says:

      Heh. Okay, you got me. I like using the term “cognitive dissonance” to refer to anything where the brain stumbles due to context switching. But you are, indeed, correct. That is not the true definition of the term. So I relent. I will instead use the more technical: “brain hurt.” ;)

      • Ok, so why haven’t you changed the text of the article? You are completely missusing a clearly defined term.

        People who know what cognitive dissonance means are going to read your article and think you are a little silly. People who don’t know what cognitive dissonance means are going to read your article and assume that you have used the term correctly. Do you really want to be responsible for making the world just a little bit dumber?

        • M. E. Patterson says:

          The surprising aggressiveness of your comment on a months-old blog post notwithstanding, I’ll approve it and answer your question, since this raises a subject that is important to me:

          I don’t believe in blog post revisionism. That is, what I posted is what I posted. The commentor rightly took me to task for misusing a cognitive psychology term, and I accepted that criticism in the comments, albeit with a response that was a little tongue-in-cheek (really, guys, this is a programming blog… does anyone except me to be an expert on psychology?). But I don’t believe in going back and changing my original post text. The post and the comments are inextricably linked. Changing the post is tantamount to revising history to make oneself look smarter, and I hate blogs that do that. I wrote what I wrote. The comments thread annotates that. Deal with it.

          • Philip P. says:

            @Liam McLellan, you state that the author of this post is “completely missusing [sic] a clearly defined term.” Ignoring your misspelling of misuse, and forgetting the negative impression it has made on your grasp of the English language, allow me to add some clarification relating to the use of “cognitive dissonance” in this post. I’ll assume it was a typographical error committed in your haste to rectify what you perceive to be a gross contravention of the semantic code. @Sigi, the following may also be of interest to you.

            Let me first acknowledge that I am very aware of the theory of “Cognitive Dissonance” in Psychology, and that I am also aware that without context I would assume such to refer to exactly that. However you fail to observe that “Cognitive Dissonance” has entered into the English language as “cognitive dissonance” purely as a result of the popularisation of this theory and has been current in this fashion only since the nineteen-forties.

            However this taking on of a new meaning does not in anyway preclude M.E. Patterson for using the term in the way in which it would have been used before this theory was formalised and in the sense of the two words being used: cognitive, pertaining to cognition; and dissonance, pertaining to incongruity. As a programmer (with a background in linguistics), I at no point thought that he was referring to the theory in Psychology but took it to mean, in the sense that the author has since clarified, a discord in the mind resulting from two contradictory (in terms of mental processes arising from different implementation paradigms) approaches to describing what is essentially the same; the document structure.

            To jump on his back for what you perceive to be an incorrect usage of this term betrays an ignorance of linguistic register, i.e. that some terms have different meanings in different contexts. To alert readers that this term is not confined to psychology alone functions in opposite fashion to the behaviour you say will occur, namely that reading this blog will not make anyone “dumber” by seeing the term used in this context, but rather, those coming from a knowledge of psychology, will in fact be alerted to the fact that these two words have a broader application than their narrow application within that field. This I would hope should make someone more intelligent, not less so.

            Shame on you; not for your ignorance, but for your zeal in propagating your ignorance to others.

  23. Social comments and analytics for this post…

    This post was mentioned on Twitter by mepatterson: Why use HAML (and SASS)? I already know HTML. http://is.gd/7zKRV

  24. @Thibaut – You can call an ERB partial from a Haml partial. Or, you can embed your ERB directly into the Haml file with the :erb filter (http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#erb-filter)

  25. I have one question (the only thing that bogs me about HAML currently): if I have a complicated HTML snippet (typically, some stuff to copy-paste in there, provided by a third party service), is there some way to put it in the HAML template as-is, without any modification ?

    Should I have an ERB subpartial or something ?


    – Thibaut

    • M. E. Patterson says:

      Good question! The answer all depends on the context of what you’re trying to copy-paste in. I would argue that for 99% of stuff out there, you should be able to translate it to HAML pretty easily. If you can’t, you should question why you’re putting such complicated code from a third-party into your app in the first place!

      If you’re still getting used to HAML, installing the gem gives you access to a great command-line utility “html2haml” … you can run this against any html file or even an erb file and it will do its best to produce a haml equivalent.

      html2haml my_html_chunk.html.erb my_new_hotness.html.haml

      But sometimes, sometimes, you’ve just got to put something weird on the page and you can’t come up with any better way. Fortunately, HAML provides some options. Depending on *what* your snippet actually is (is it a chunk of ruby, or html, or css, or javascript, or what?), you may be able to use some of HAML’s handy-dandy filters.

      And finally, if none of that helps, and you need to put some complicated chunk of ERB into your app and you’re afraid to try and translate it to HAML, you have the answer already. HAML and ERB play nice together. You can just call a partial like:

      = render :partial => 'thirdpartything'

      … as always, Rails will expect to find something called “_thirdpartything.html.erb” in the view folder of the same template.

      • > Good question! The answer all depends on the context of what you’re trying to copy-paste in. I would argue that for 99%
        > of stuff out there, you should be able to translate it to HAML pretty easily. If you can’t, you should question why you’re
        > putting such complicated code from a third-party into your app in the first place!

        I don’t agree here – I wouldn’t use a tool that get in the way too long (and thanks Nathan/Aaron, there are solutions, so it doesn’t!).

        The situation I’m referring to is when you embed carefully crafted widgets, and where the TOS of the third-party system does not forget to mention that if you don’t exactly use this code, the service may not work (think affiliation, widgets etc).

        Rewriting these in HAML is just not an option, because it really defeats the purpose of HAML (for me: faster development, reduced maintenance).

        I would have to rewrite each snippet I integrate (there are many), each time they change (they do change), just to start using HAML, if I didn’t have a way to escape out here!

        Hope this clarifies my point :)

        Thanks again for the great article,

        – Thibaut

    • You can use the


      filter to include HTML text verbatim, as long as it’s properly indented.