ERB模板添加到页面的不同部分

时间:2013-09-06 14:51:10

标签: ruby ruby-on-rails-3 erb

专家

说,我想以一种在线图书结构呈现页面:

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-code。 也许有办法只做一个循环?

1 个答案:

答案 0 :(得分:0)

正如其他人所说,你拥有的东西没有错。这是一种非常简单的方法,只使用一个循环:

<% toc, body = '', '' %>
<% @chapters.each_with_index do |chapter, n| %>
  <% toc << %Q{
    <a href="#c_#{n}">#{n}. #{chapter.title}</a>
  } %>
  <% body << %Q{
    <h2 id="c_#{n}">#{n}. #{chapter.title}</h2>
    <p>#{chapter.text}</p>
  } %>  
<% end %>
<%= raw toc %>
<hr/>
<%= raw body %>

您可能希望确保要转义的所有内容都已转义。你可能也想把它变成一个帮手。