Ruby-on-rails 如何在Haml中编写if条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8026619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write if-condition in Haml?
提问by Thillai Narayanan
How to write ifand if-elsestatements in Haml for a Ruby on Rails application?
如何在 Haml 中为 Ruby on Rails 应用程序编写if和if-else语句?
回答by bilash.saha
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.
HAML 是基于缩进的,解析器可能很棘手。您不需要在 Haml 中使用“-end”。改用缩进。在 Haml 中,每当在 Ruby 求值命令之后增加缩进时,就会开始一个块。当缩进减少时结束。示例 if else 块如下。
- 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 条件,则
- if current_user
= link_to 'Logout', logout_path
回答by Pratik Ganvir
In haml two operators are used for ruby code.
在 haml 中,两个运算符用于 ruby 代码。
=is used for ruby code which is evaluated and gets inserted into document.
=用于评估并插入到文档中的 ruby 代码。
Example:
例子:
= form_for @user
-is used for ruby code which is evaluated and NOT get inserted into document.
-用于评估并且不会插入到文档中的 ruby 代码。
Example:
例子:
- if @user.signed_in?
= "Hi"
- else
= "Please sign in!"
回答by Michelle Tilley
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.
在haml 中,使用-(破折号)表示一行是Ruby 代码。此外,缩进级别表示块级别。将两者结合用于 if/else 语句。
- 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:
与ERB中的以下代码相同:
<% if signed_in? %>
<li><%= link_to "Sign out", sign_out_path %></li>
<% else %>
<li><%= link_to "Sign in", sign_in_path %></li>
<% end %>
回答by Anton Sergeyev
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}
回答by gkstr1
Here are two links:
这里有两个链接:
The first one is a converter- you can enter html or erb snippets and you get haml!
第一个是转换器——你可以输入 html 或 erb 片段,你会得到 haml!

