views:

151

answers:

2
+3  Q: 

Haml formatting

I'm new to haml, so I'm still trying to figure out the formatting.

I have an index.haml file with the following code.

%h1
  Welcome to Solidarity

Hello,
= @profile.first_name
!

It renders like this:

Welcome to Solidarity
Hello, user !

Here's the page source:

<h1>
  Welcome to Solidarity
</h1>
Hello,
frances
!

It has a space between @profile.first_name and the exclamation mark. Why is that? And, how do I fix it?

+5  A: 
%h1 Welcome to Solidarity
Hello, #{@profile.first_name}!
Please #{link_to 'post a comment', new_comment_path}!

becomes

<h1>Welcome to Solidarity</h1>
Hello, John!
Please <a href="/comments/new">post a comment</a>!

Please keep in mind that in Rails 2 and Haml 2, you must properly html-escape anything you send to the browser (ht nex3):

Hello, #{h @profile.first_name}!

In Rails 3 and Haml 3, everything is escaped by default, so you can simply do:

Hello, #{@profile.first_name}!
Justice
Thanks!Also, similarly, link_to calls have the extra space at the end. How should those be resolved?
Teef L
Edited my answer to add an example of `link_to`.
Justice
Don't forget to HTML-escape the username!
nex3
Thanks nex3. I edited my answer to include escaping in Rails 2.
Justice
+3  A: 

You can also use "alligators" to "eat" the white space before or after a tag. From the haml-lang docs:

%img
%pre><
  foo
  bar
%img

is compiled to:

<img /><pre>foo
bar</pre><img />

While this would have also solved your problem here, the solution given by Justice is the appropriate markup for this scenario. Just thought I'd mention it.

chadoh