Rails布局动态渲染

时间:2013-10-22 07:50:09

标签: ruby-on-rails ruby-on-rails-4 pjax turbolinks

我有一个Ruby on Rails应用程序,它的最基本级别包括两个面板,左侧和右侧面板。我想要的是将它用作布局,并在控制器中能够像render <view_name>, <right or left panel>那样渲染,这样,与turbolinks一起,只动态创建左侧或右侧面板。

我搜索了互联网,但没有找到像我这样的例子。我确定这是可行的但是怎么样? 编辑:它应该能够在Android的chrome中运行。 一种解决方案是在第一个请求上呈现所有视图,当我单击链接面板时,隐藏并显示,但我不认为这是好的。任何意见? enter image description here

3 个答案:

答案 0 :(得分:1)

不幸的是,这种情况不可能与turbolinks一起使用,也不能用pjax本身(有多个所谓的pjax容器)。

Turbolinks总是取代整个身体元素的内容。 Pjax总是用pjax-container数据属性替换元素的内容。

当然有办法做到这一点。抛弃客户端javascript框架,您可以执行ajax请求并返回js响应。

从头顶你可以看到类似这样的视图:

<强> index.html.erb

<%= link_to 'Show', show_path, remote: true %>

<强>控制器

def show
  # Do the work, fetch data from database etc.

  # Keeping both formats ensures that when you hit the url directly 
  # the whole page gets rendered as usual (show.html.erb), 
  # when the request is an ajax request using the view snipper above just
  # the javascript for replacing the content of a single panel is rendered (show.js.erb)
  #
  # Rails is smart enough so it should not be required to include the respond_to block
  # in the controller, Rails automagically chooses an appropriate response format
  # based on the request, you only need to have the views in place,
  # but I keep it here so you get a picture.
  respond_to do |format|
    format.html
    format.js
  end

<强> show.js.erb

$('.right-panel').html('<%= j render partial: "something" %>')

答案 1 :(得分:0)

经过一些研究,我得出以下结论:

除非你设定一些限制,否则我试图做的事情是不可能的。

两个面板中只有一个可以呈现存储在浏览历史记录中的“操作”。如果两个面板都呈现存储在浏览历史记录中的操作,则导航很可能无法按预期工作。

考虑到这一点,我意识到我真正需要的是在左侧面板中呈现导航感知操作,并在右侧面板中呈现其他内容(我称之为实用程序)。例如,我在这样一个面板中呈现的一件事是聊天面板。这就是facebook如何使用它的聊天。

所以基本上我可以使用标准turbolink来处理存储浏览历史记录的请求以及类似pjax的“Utils”面板。唯一的问题是Turbolinks完全呈现整个页面,即使你发送一小段html作为回应。

为了解决这个问题,我最终使用了wiselinks,这是turbolinks和pjax的完美结合。此外,与pjax不同,wiselink甚至可以处理表单。

答案 2 :(得分:0)

我不知道它是否是最佳做法,但我需要类似的东西,这就是我所做的:

我有这个布局

1st panel | 2nd panel  | 3rd panel
Site Menu | Posts List | Article Show

要始终呈现帖子列表,我需要添加到我的应用程序控制器:

class ApplicationController < ActionController::Base
  before_action :set_posts

  def set_posts
    @posts = Post.all
  end
end

然后在我的布局中,这就是我所做的:

%body
    #site-wrapper
      #site-canvas
        #reading-list
          #reading-nav-block 
          = render 'posts/list'

        #article-show
          #article-nav-block
          #article-content-block
            = yield
        #site-menu
          #logo-block
          .menu

基本上我将帖子#index提取到帖子#_list partial并设置变量,在所有布局中渲染post / _list。结果如下:

enter image description here

相关问题