0

Ruby on Rails 应用程序,我有一个带有超链接的“引导”行图像。我只想显示其中包含内容的内容。

这是一个例子:

<div class="span3">
    <h5 class="pagination-centered">
        <%= link_to (image_tag "/img/folder.jpg", alt: "Buyer's Guides", width: "75px"), action: "index", filter: @filter, type: "buyers_guides" %>
        <%= link_to "Buyer's Guides", action: "index", filter: @filter, type: "buyers_guides" %>
    </h5>
</div>
<div class="span3">
    <h5 class="pagination-centered">
        <%= link_to (image_tag "/img/folder.jpg", alt: "Datasheets", width: "75px"), action: "index", filter: @filter, type: "datasheets" %>
        <%= link_to "Datasheets", action: "index", filter: @filter, type: "datasheets" %>
    </h5>
</div>

使用 if else 语句可以吗?否则,否则?

或者控制器呢?

class Users::MarketingController < ApplicationController
def index
    @filter = params[:filter]
    @type = params[:type]

if @filter
        if @type    
        arrays_of_strings_to_check_against = ['logos', 'datasheets', 'buyers_guides', 'videos', 'web_banners', 'presentations', 'documents', 'press_releases' ]

        if arrays_of_strings_to_check_against.any?{ |o| @type =~ /\b#{Regexp.escape(o)}\b/ }
            base_dir = "public/files/marketing"
            @files = Dir.glob("#{base_dir}/voip/#{@filter}/#{@type.downcase}/*.[a-z]*")
            @view = "files"
        else    
            @view = 'types'
        end
    else
        @view = 'types'
    end
else
    @view = "category"
end
end

结尾

对此并不陌生,并试图学习良好的做法。谢谢

4

2 回答 2

3

是的,if/else通常在这种情况下使用,尽管绝对丑陋。您也可以使用condition ? do_if_true : do_if_false符号,这在这里很方便。

<% if has_content_condition %>
 <div class="span3">
  <h5 class="pagination-centered">
    <%= link_to (image_tag "/img/folder.jpg", alt: "Buyer's Guides", width: "75px"), action: "index", filter: @filter, type: "buyers_guides" %>
    <%= link_to "Buyer's Guides", action: "index", filter: @filter, type: "buyers_guides" %>
  </h5>
 </div>
 <div class="span3">
  <h5 class="pagination-centered">
    <%= link_to (image_tag "/img/folder.jpg", alt: "Datasheets", width: "75px"), action: "index", filter: @filter, type: "datasheets" %>
    <%= link_to "Datasheets", action: "index", filter: @filter, type: "datasheets" %>
  </h5>
 </div>
<% end %>

我不确定这是否是您的想法。如果不清楚,请发表评论,我很乐意提供帮助。=)

于 2013-08-16T19:47:01.947 回答
0

如果我理解正确,您也可以这样做:

if x.present?
  x
end

所以例如

@image = image.find(params[:id])
if @image.present?
  <div class="span3">
    <h5 class="pagination-centered">
      <%= link_to (image_tag "/img/folder.jpg", alt: "Buyer's Guides", width: "75px"), action: "index", filter: @filter, type: "buyers_guides" %>
      <%= link_to "Buyer's Guides", action: "index", filter: @filter, type: "buyers_guides" %>
    </h5>
  </div>
end
于 2013-08-16T20:01:23.737 回答