if,elsif,else语句html erb初学者

问题描述 投票:8回答:2

我在html.erb中遇到if,else if,else语句时遇到问题。我在erb中看到了很多关于if / else语句的问题但没有包含elsif的问题,所以我想我会请求帮助。

这是我的html.erb:

<% if logged_in? %>

          <ul class = "nav navbar-nav pull-right">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
              Account <b class="caret"></b>
            </a>

          <ul class="dropdown-menu pull-right">
                  <li><%= link_to "Profile", current_user %></li>
                  <li><%= link_to "Settings", edit_user_path(current_user) %></li>
                  <li class="divider"></li>
                  <li>
                    <%= link_to "Log out", logout_path, method: "delete" %>
            </li>
          </ul>
          </li>
        </ul>



     <% elsif has_booth?(current_user.id) %>

      <ul>

        <li>TEST</li>

      </ul>



<% else %>
        <ul class="nav navbar-nav pull-right">
          <li><%= link_to "Sign Up", signup_path %></li>
          <li><%= link_to "Log in", login_path %></li>
        </ul>
      <% end %>

这是我的has_booths方法:

module BoothsHelper

def has_booth?(user_id)
  Booth.exists?(user_id: user_id)
end 

end

我希望标题导航为不同的用户提供三种不同类型的内容。登录用户,已创建booth的登录用户以及已注销用户。到目前为止,我似乎只能在三项工作中做出2项。我试过改变

<% elsif has_booth?(current_user.id) %>

<% elsif logged_in? && has_booth?(current_user.id) %>

那也不起作用。我正确地写了我的陈述吗?任何想法都赞赏。谢谢。

ruby-on-rails-4 erb
2个回答
18
投票

问题是你的第一个条件是真的,所以它停在那里。你的第一个条件:

<% if logged_in? %>

即使他们没有展位也永远不会到达elsif,因为第一个条件是真的。你要么需要:

<% if logged_in? && has_booth?(current_user.id) %>
  // code
<% elsif logged_in? && !has_booth?(current_user.id) %>
  // code
<% else %>
  // code
<% end %>

或者它可能是一个更简洁的方法将它们分成两个if / else:

<% if logged_in? %>
  <% if has_booth?(current_user.id) %>
    // code
  <% else %>
    // code
  <% end %>
<% else %>
  // code
<% end %>

0
投票

更简洁的方法是压扁语句,首先处理未登录的条件,这样你就不必测试它是否有一个展位:

<% if !logged_in? %>
  // not logged in code
<% elsif has_booth?(current_user.id) %>
  // logged in and has booth code
<% else %> 
  // logged in and does not have booth code
<% end %>

你也可以使用unless logged_in?,但是else和elsif在语义上没有那么多意义,除非它因此不能清楚地阅读。

© www.soinside.com 2019 - 2024. All rights reserved.