加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在模板中循环

发布时间:2020-12-16 19:55:17 所属栏目:百科 来源:网络整理
导读:我的模板看起来像: h2Oracle/h2 % @q_oracle.each do |q| % %= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) % /br % end % h2Ruby and Rails/h2 % @q_ruby.each do
我的模板看起来像:
<h2>Oracle</h2>

  <% @q_oracle.each do |q| %>
    <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %>  </br>

  <% end %>


  <h2>Ruby and Rails</h2>

  <% @q_ruby.each do |q| %>
    <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %>  </br>

  <% end %>

所以temlate包括静态标题(h2)和循环遍历数组.我正在寻找避免在我的模板中复制粘贴代码的方式.就像是:

@hash = { 'Oracle' => @q_oracle,'Ruby and Rails' => @q_ruby }

@hash.each { |@t,@a|

  <h2>@t</h2>

  <% @a.each do |q| %>
    <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %>  </br>

  <% end %>
}

可能吗?

解决方法

是的,你可以做到

Ruby 1.9解决方案

在Ruby 1.8中,这个解决方案可以在标题顺序无关紧要时使用.在Ruby 1.9标题中,它们将以哈希方式插入.

只需将此变量放在您的控制器操作中即可:

@hash = { 'Oracle' => @q_oracle,'Ruby and Rails' => @q_ruby }

并从您的视图访问此变量:

<% @hash.each do |t,a| %>
  <h2><%= t %></h2>
  <% a.each do |q| %>
    <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %>  </br>
  <% end %>
<% end %>

具有排序键的Ruby 1.8

这种方法排序键,使其按字母顺序显示.

<% @hash.keys.sort.each do |t| %>
  <h2><%= t %></h2>
  <% @hash[t].each do |q| %>
    <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %>  </br>
  <% end %>
<% end %>

Ruby 1.8与数组

这种方法在任何Ruby版本中都将像Ruby 1.9一样运行 – 标题会按照添加的方式出现.

变量@hash必须初始化为:

@hash = [ ['Oracle',@q_oracle],['Ruby and Rails',@q_ruby] ]

视图必须更新为:

<% @hash.each do |title_with_questions| %>
  <h2><%= title_with_questions[0] %></h2>
  <% title_with_questions[1].each do |q| %>
    <%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s,'https://stackoverflow.com/' + q.question_answers_url) %>  </br>
  <% end %>
<% end %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读