Read more

Removing white space after links in HAML

Dominik Schöler
May 24, 2012Software engineer at makandra GmbH

TL;DR

%p
  #{link_to "label", "url"}!

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

Haml is a great engine for writing shorter, readable HTML. However, there is one thing that troubles me regularly. Consider this Haml code:

%p
  Visit our homepage at
  = link_to "www.makandra.com", "http://www.makandra.com"
  !

Haml will insert a space around the generated link, the result is this (see the space before the exclamation mark!):

<p>
  Visit our website at <a href="http://www.makandra.com">www.makandra.com</a> !
</p>

They suggest to use a Haml helper, but to me this solution is ugly and too much overhead.

 %p
  Visit our homepage at
  - succeed('!') do
    = link_to "www.makandra.com", "http://www.makandra.com"

I prefer a workaround I found on stackoverflow Show archive.org snapshot :

%p
  Visit our homepage at
  #{link_to "www.makandra.com", "http://www.makandra.com"}!

If you like, for some use cases this may be helpful, too:

%p
  Visit our homepage at
  = link_to("www.makandra.com", "http://www.makandra.com") + "!"

To remove whitespaces around an element created with HAML syntax, use >:

%p 
  Visit our homepage at
  %a{:href => "http://www.makandra.com"} www.makandra.com
  %span> !
Posted by Dominik Schöler to makandra dev (2012-05-24 11:02)