How to write if-condition in Haml?

前端 未结 5 1417
长发绾君心
长发绾君心 2021-01-31 00:55

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

相关标签:
5条回答
  • 2021-01-31 01:37

    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 %>
    
    0 讨论(0)
  • 2021-01-31 01:41

    If you want to put condition inside your tag

    %section{:class => "#{'new-class' if controller.action_name == 'index'}"}
    

    UPDATE

    Here is another variation

    %nav(class="navbar"){class: content_for?(:navbar_class) ? yield(:navbar_class) : nil}
    
    0 讨论(0)
  • 2021-01-31 01:45

    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
    
    0 讨论(0)
  • 2021-01-31 01:45

    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!"
    
    0 讨论(0)
  • 2021-01-31 01:51

    Here are two links:

    1. https://html2haml.herokuapp.com/
    2. http://haml.info/tutorial.html

    The first one is a converter- you can enter html or erb snippets and you get haml!

    0 讨论(0)
提交回复
热议问题