【问题标题】:Ruby on Rails 3 : Playing with viewsRuby on Rails 3:玩视图
【发布时间】:2011-08-21 04:31:11
【问题描述】:

我很抱歉我的英语不好。我只是尝试描述我的问题。 :) 我有一个应用程序布局,可以在正文中显示帖子。我还有另一个收益 :footerpost3 用于在页脚上显示最近帖子的标题。

当我在 localhost:3000 时,yield :footerpost3 正确显示最近的标题。但是当我点击一个帖子链接时,即 url 是 localhost:3000/posts/3,yield :footerpost3 什么也不显示。

这是我的代码: app/views/layout/application.html.erb

<!-- begin footer comment widget -->
  <div class="footer_list widget_recent_comments">
    <div class="title"><h5>Artikel Terkini</h5></div>
      <%= yield :footerpost3 %>             
    </div>
<!-- end footer comment widget -->

app/views/store/index.html.erb

<% content_for :footerpost3 do %>
    <% @postsMain.each do |dopostAll| %>
        <div class="entry">
            <ul>
                <li class="recentcomments"><%= link_to dopostAll.title, dopostAll %></li>
            </ul>
        </div>                          
    <% end %>
<% end %>

我希望我的问题很容易理解.. :)

【问题讨论】:

    标签: ruby views


    【解决方案1】:

    看起来您的根网址是 stores#index 。 您必须在 stores#index 操作中初始化 @postsMain 并在 stores/index.html.erb 中生成 footerpost3 的 content_for。

    当您点击帖子时,您将被带到posts#show page。因此,即使在 posts#show 操作中,您也必须初始化 @postsMain 并为 footerpost3 甚至在 posts/show.html.erb 中生成内容

    【讨论】:

      【解决方案2】:

      答案就在您的问题中。您正在该块中定义“内容”footerpost3,它存在于index.html.erb 中。当你在/posts/3 上时,index.html.erb 不会被渲染,而是show.html.erb 会被渲染。

      要解决这个问题,您还需要在 show.html.erb 模板中添加内容。

      您可以通过多种方式解决此问题。使用嵌套布局就是其中之一。例如,您可以在app/views/layout/posts.html.erb 创建一个帖子布局,如下所示:

      <% content_for :footerpost3 do %>
          <% @postsMain.each do |dopostAll| %>
              <div class="entry">
                  <ul>
                      <li class="recentcomments"><%= link_to dopostAll.title, dopostAll %></li>
                  </ul>
              </div>                          
          <% end %>
      <% end %>
      
      <%= render :file => 'layouts/application' %>
      

      这样,您的 PostsController 的所有视图都将使用此布局,它只是添加您的页脚内容,然后呈现 application_layout。

      【讨论】:

      • 所以我必须在每隔一个视图中插入一个 'layouts/application' %> 代码?有没有简单的方法?像应用程序助手?老实说,我不明白应用程序助手:)
      • 不是每个视图。这个例子展示了你可以如何使用布局来做到这一点。您的所有帖子视图(索引、显示、新建、编辑)将自动在此布局中呈现。所以你只会把它放在一个地方。诀窍是您必须确保在此布局内呈现的所有视图中都定义了@postsMain,否则它们会中断。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多