Removing white space after links in HAML

Updated . Posted . Visible to the public.

TL;DR

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

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> !
Profile picture of Dominik Schöler
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2012-05-24 09:02)