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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)