【问题标题】:ERB template add to different parts of the pageERB 模板添加到页面的不同部分
【发布时间】: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


【解决方案1】:

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

<% 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 %>

你会想要确保你想要逃脱的一切都被逃脱了。你可能还想把它移到一个帮助器中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多