【问题标题】:How to display several image_tag inside an iteration in a helper如何在帮助程序的迭代中显示多个 image_tag
【发布时间】:2011-05-14 17:44:39
【问题描述】:

我正在尝试创建一个帮助器来根据模型属性显示评级星。

我有以下几点:

  def show_profile_stars(profile)
    content_tag :span, :class => 'stars' do
      profile.stars.times do
        image_tag("stars.gif", :size => "30x30", :class => "gold")
      end
    end
  end

'stars' 是一个整数字段。

但它不是渲染图像标签,而是按字面显示“星星”数字。

如果我只放了 image_tag 而没有迭代块,它确实显示了图像,那么问题出在迭代上。

我想我错过了一些关于接收块的方法(我还是 RoR 的新手)。

有什么帮助吗?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby iteration helpers


    【解决方案1】:

    两件事,这不是在 CSS 中使用跨度上的类来完成(例如,一星、两星等)吗?

    无论如何,实际做你想做的尝试:

    stars = []
    profile.stars.times { stars << image_tag("stars.gif", :size => "30x30", :class => "gold") }
    content_tag :span, stars.join("\n").html_safe, :class => "stars"
    

    【讨论】:

    • 我只有一张 1 星的图片。人们可以拥有从 0 星到许多星...所以我需要根据属性显示正确的星数。我试试你的方法,谢谢!
    【解决方案2】:

    使用concat 助手:

    def show_profile_stars(profile)
      content_tag :span, :class => 'stars' do
        profile.stars.times do
          concat(image_tag("stars.gif", :size => "30x30", :class => "gold"))
        end
    
        nil
      end
    end
    

    您还需要在content_tag 的末尾返回nil,这样它就不会输出stars

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      相关资源
      最近更新 更多