Of course, HAML really shines when you mix it with Ruby and a framework such as Rails or Merb. You can interpret and display Ruby code with the equal sign (=) operator (equivalent to <%= in ERB, and embed statements and blocks with the minus sign (-). This code…
- name = 'Zeppo'
- names = %w( Groucho Chico Harpo )
- names.each do |n|
Like an element, a block of code is defined with active white space.
Like HAML, SaSS provides an outline-like syntax to define styles. For comparsion, SaSS is on the left, and traditional CSS is at right. Again, you can manually produce the CSS from its shorthand with the sass command.
!listing_color = white
You can create constants with the exclamation point (!). You can then use those constants throughout your styles. You can also perform arithmetic, concatenation, and other operations on the constants.
To create a style, name the kind of element, an ID, or class as you would in CSS, then indent and list the attributes and values. Here, I’ve used one form of syntax, :font-size 1.2em. If you prefer, you can also use the CSS-like syntax, font-size: 1.2em, but omit the trailing semicolon (;).
To create a style to affect a nested element, simply indent the element within another and define your attributes. The example here defines styles for a paragraph of class list that occurs within the div main. Look at the CSS SaSS generates. The stylesheet is still a flat-file, but SaSS uses indentation to reinforce the relationship between the two elements.
To conserve typing, SaSS lets you group like attributes in a namespace. For example, the namespace font contains family, size, and weight. You can use a namespace for background, border, and margin, among others.
Beyond the lack of structure in a stylesheet, another problem is repetition. Styles often share the same attribute or set of attributes, yet rather than write something akin to …
There is even more to like about HAML and SaSS, so read the project website, which has a tutorial and expansive documentation with examples.
If you are developing in Rails, you can download the gem and run the generator to embed HAML in your project in moments. HAML template files are named .html.haml; SaSS files are named .sass and typically are placed in public/stylesheets/sass. When your application runs, HAML generates the corresponding CSS for each SaSS file and places the resulting stylesheet in public/stylesheets. Simply reference the CSS file with =stylesheet_link_tag in your layout.
Now, what will you do with all those saved keystrokes?