HAML: remove white space after “link_to”

2019-04-03 03:41发布

问题:

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?

回答1:

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 :(



回答2:

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



回答3:

You could but the > on the following line.

= link_to "Login", "#"
#something_else>


回答4:

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>.



回答5:

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')