Ruby on Rails: conditionally display a partial

前端 未结 3 685
一个人的身影
一个人的身影 2021-02-11 14:05

I\'m not sure if I\'m doing the best approach here, but I have a block of data that I want to show after a search is done and to not be there at all before. First of all, there

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-11 14:39

    Ruby allows you to do nice things like this:

    <%= render :partial => "foo/bar" if @conditions %>
    

    To make this a bit easier to read and understand, it can be written as:

    <%= render(:partial => "foo/bar") if @conditions %>
    

    render is a function, and you pass it a hash that tells it which partial to render. Ruby allows you to put things on one line (which often makes them more readable and concise, especially in views), so the if @conditions section is just a regular if statement. It can also be done like:

    <% if @conditions %>
      <%= render :partial => "foo/bar" %>
    <% end %>
    

    Edit:

    Ruby also allows you to use the unless keyword in place of if. This makes code even more readable, and stops you from having to do negative comparisons.

    <%= render :partial => "foo/bar" if !@conditions %>
    #becomes
    <%= render :partial => "foo/bar" unless @conditions %>
    

提交回复
热议问题