30

The following code leaves a white space in HTML:

= link_to "Login", "#"

Normally, HAML allows to remove it by putting ">" at the end of the line, for example:

%input#query{:type => "text", :value => "Search"}>

However, that seems to be impossible, when Rails code is inserted.

How do I fix this?

krn
  • 6,715
  • 14
  • 59
  • 82
  • 1
    This answer is much, much better: http://stackoverflow.com/questions/1311428/haml-control-whitespace-around-text – rking Jul 13 '12 at 22:22

5 Answers5

25

The solution with span is not ideal as it adds an unnecessary html tag that will require processing, if you want to avoid the <span> you should use HAML's succeed:

= succeed "," do
  = link_to "Login", "#"

which will result in the following HTML being rendered:

Login,

rather than

Login ,

Note that if you want to achieve the following result:

Login,Profile

i.e. no whitespace whatsoever between the comma and two links you should do the following:

= succeed link_to "Profile", '#' do
  = succeed "," do
    = link_to "Login", '#'

which gets pretty tedious

Georgi
  • 734
  • 6
  • 12
  • What a gem. This the "right" way to do it. Documentation: http://haml.info/docs/yardoc/Haml/Helpers.html#succeed-instance_method – Benji Aug 18 '15 at 19:46
  • There is also `precede` which doesn't require you to turn the order around. http://haml.info/docs/yardoc/Haml/Helpers.html#precede-instance_method – thutt Feb 26 '19 at 11:12
19

How about this?

%span>= link_to "Login", "#"

It adds an extra span around the link, but those are pretty harmless.

I find haml can have a bit of a problem with some of these corner cases :(

Blake Taylor
  • 9,217
  • 5
  • 38
  • 41
8

You could but the > on the following line.

= link_to "Login", "#"
#something_else>
Blake Taylor
  • 9,217
  • 5
  • 38
  • 41
  • 3
    Thanks, %span{:style => "display:none;"}> seems to work fine, but using it multiple times is such a terrible solution... I hope there is a better way. – krn Apr 15 '11 at 17:57
1

For anyone coming to this thread I find I most need to remove whitespace most when a link is at the end of a sentence.

I'll usually use:

= link_to("Login", '#) + '. '

which results in:

<a href="#">Login</a>.

Niels
  • 353
  • 1
  • 6
  • 15
0

Here's another poor alternative solution for removing spaces between several rails lines using the :ruby filter:

:ruby
             haml_io.write f.hidden_field('params_ar[][units]', value: 'time')
             haml_io.write f.text_field("params_ar[][minutes]", value:pars[param_num][:minutes],class:'time-input minutes', placeholder:'mm')
             haml_io.write ':'
             haml_io.write f.text_field("params_ar[][seconds]", value:pars[param_num][:seconds],class:'time-input seconds' ,placeholder:'ss')
João Costa
  • 344
  • 3
  • 11