【问题标题】:Rails content_tag for <ul> element<ul> 元素的 Rails content_tag
【发布时间】:2013-12-04 21:26:21
【问题描述】:

如何使用 content_tag 帮助程序获得以下 html 输出?

  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>

这是我目前拥有的

  content_tag(:ul) do
    a=*(1..5)
    a.each do |step_number|
      content_tag(:li, class: "step") do
        puts step_number
      end
    end
  end

更新 - 回答

感谢 Peter 在下面的 Loop & output content_tags within content_tag in helper 链接,我在 li 项目上缺少 concat

  content_tag :ul do
    items.collect do |step_number|
      concat(content_tag(:li, step_number, class: "step"))
    end
  end

【问题讨论】:

  • (我认为 splat * 不会像您认为的那样做。)您目前有什么输出?
  • @Phlip 他似乎只是要创建一个用于迭代的数组,在这种情况下,splat a) 将不起作用并且 B) 没有必要... OP:尝试 (1.. 5).每个都做... ;)
  • 如何将此解决方案用于嵌套的解决方案

标签: html ruby-on-rails content-tag


【解决方案1】:

我猜你需要解决的只是

content_tag(:ul) do
  (1..5).to_a.map do
    content_tag(:li, step_number, class: "step)
  end.reduce(&:+)
end

这应该可以完成工作!

【讨论】:

  • 我把我不得不做的 splat 改成了 Anton 的 1.upto 5,但这不起作用(我还添加了你已经放弃的结束 "
  • 用地图替换 upto 就可以了。由于这会生成连接,因此您必须在末尾添加 reduce
  • reduce(&amp;:+) 应该在第一个 end 之后。另外,我通常更喜欢.join('') 而不是reduce
【解决方案2】:

它对我有用。

content_tag(:ul, :class => 'a class') do
  (1..5).each do |item|
    concat content_tag(:li, item)
  end
end

<ul class="a class">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多