Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write if-condition in Haml?

How to write if and if-else statements in Haml for a Ruby on Rails application?

like image 909
Thillai Narayanan Avatar asked Nov 06 '11 11:11

Thillai Narayanan


2 Answers

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 
like image 144
bilash.saha Avatar answered Sep 25 '22 02:09

bilash.saha


In haml two operators are used for ruby code.

  • = is used for ruby code which is evaluated and gets inserted into document.

Example:

= form_for @user   
  • - is used for ruby code which is evaluated and NOT get inserted into document.

Example:

- if @user.signed_in?     = "Hi"   - else     = "Please sign in!" 
like image 33
Pratik Ganvir Avatar answered Sep 25 '22 02:09

Pratik Ganvir