How to write if and if-else statements in Haml for a Ruby on Rails application?
85
votes
4 Answers
133
votes
HAML is indentation based , and the parser can be tricky.You don't need to use "- end" in Haml. Use indentation instead.In Haml,a block begins whenever the indentation is increased after a Ruby evaluation command. It ends when the indentation decreases.Sample if else block as follows.
- if condition
= something
- else
= something_else
A practical example
- if current_user
= link_to 'Logout', logout_path
- else
= link_to 'Login', login_path
Edit : If you just want to use if condition then
- if current_user
= link_to 'Logout', logout_path
18
votes
9
votes
In haml, use the - (dash) to indicate a line is Ruby code. Furthermore, indention level indicates block level. Combine the two for if/else statements.
- if signed_in?
%li= link_to "Sign out", sign_out_path
- else
%li= link_to "Sign in", sign_in_path
is the same as the following code in ERB:
<% if signed_in? %>
<li><%= link_to "Sign out", sign_out_path %></li>
<% else %>
<li><%= link_to "Sign in", sign_in_path %></li>
<% end %>