【发布时间】:2013-09-06 14:51:09
【问题描述】:
专家
说,我想以一种在线图书结构呈现页面:
Table of contents:
[link here]1. How it all began
[link here]2. Where did it go
...
1. How it all began
Text of chapter 1
...
2. Where did it go
Text of chapter 2
...
...
所以通常使用 erb 我会执行以下 ruby 代码:
<h2>Table of contents:</h2>
<% chapters.each_with_index do |chapter, n| %>
<a href="#c_<%= n %>"><%= n %>. <%= chapter.title %></a>
<% end %>
<hr/>
<% chapters.each_with_index do |chapter, n| %>
<h2 id="c_<%= n %>"><%= n %>. <%= chapter.title %></h2>
<p>
<%= chapter.text %>
</p>
<% end %>
但是,我在这里做了两个相同的循环,因为我必须同时在页面的两个不同部分插入 ruby 代码。 也许有一种方法可以只做一个循环?
【问题讨论】:
-
我认为这很好......
-
在这种情况下,有两个循环并没有让我觉得特别有问题。例如,您可以将章节文本存储在某种变量中,然后在第一个可枚举完成后输出该变量,但结果是您将得到更丑陋的代码。
-
但是,您确实有语义上不正确的标记,每个 ID 标签都使用了两次。
-
@DVG 你在哪里看到重复的 ID?
-
我的错,我完全看错了,你没有它们 :)
标签: ruby ruby-on-rails-3 erb