2011-10-08 29 views
0

我使用Ajax加载了一个模板profile_messages作为jQuery UI选项卡的一部分。然而,当它加载时,profile_messages继承我的网站的应用程序布局(页眉,页脚,一切)。我试图做一个部分,但事情没有奏效。所以我想知道是否有办法做到这一点。在Rails 3中排除应用程序布局div

jQuery的我application.js

$(function() { 
    $("#tabs").tabs({ 
     ajaxOptions: { 
      error: function(xhr, status, index, anchor) { 
       $(anchor.hash).html(
        "There was an error loading this tab. Please try again."); 
      } 
     } 
    }); 
}); 

Routes.rb

resources :profiles do 
    get :profile_messages, :on => :collection 
end 
match "/profiles/profile_messages" => "profiles#profile_messages" 

profiles#show.html.erb

<div id="tabs"> 
    <ul id="infoContainer"> 
    <li><a href="#tabs-1">About</a></li> 
    <li><%= link_to "Messages", '/profiles/profile_messages/', :id => 'qs', :remote => true %></li> 
    </ul> 
    <div id="tabs-1"> 
    </div> 
</div> 

profile_messages模板:

<div id="tabs-2"> 
<% for message in @user.messages %> 
<% end %> 
</div> 

profile_messages.js.erb

$("#tabs").html("<%= escape_javascript(render(@profile.messages)) %>"); 

profile_messages方法profiles_controller.rb

def profile_messages 
    @profile = User.find(user.id).profile #need to fix so @profile is defined for each profile, not just the current_user profile 
    @messages = User.find(@profile.user_id).messages 
    respond_to do |format| 
    format.html # index.html.erb 
    format.xml { render :xml => @messages } 
    end 
end 

那么,有什么办法可以解决应用程序布局?

更新:我得到的布局通过插入消失以下为我profile_messages

def profile_messages 
    @profile = User.find(user.id).profile 
    @messages = User.find(@profile.user_id).messages 
    respond_to do |format| 
    format.html { render :layout => nil } 
    format.xml { render :xml => @messages } 
    end 
end 

更新2:我试图呈现一个部分,但没有奏效。下面是我在profiles#show.html.erb改变:

<div id="tabs"> 
    <ul id="infoContainer"> 
    <li><a href="#tabs-1">About</a></li> 
    <li><%= link_to render(:partial => 'profiles/profile_messages'), :id => 'qs', :remote => true do %>Messages<span>&nbsp;</span><% end %></li> 
    </ul> 
    <div> 
    </div> 
</div> 

然而,这荷载分项中<ul id="infoContainer">

回答

4

在控制器方面,添加在“秀”的结束动作:

render :layout => nil 

或者,如果你从其他地方渲染,只需添加:layout => nil选项来渲染。

更好的解决方案是将其设置为局部和调用渲染:partial =>“profile_messages/profile_message”(如果您的模板位于app/views/profile_messages/_profile_message.html.erb中 - 注意_中的_文件名!)

而是采用escape_javascript它实际上是简单沟“的报价和使用(渲染也...)。to_json。

+0

我会给这个去。谢谢! – tvalent2

+0

我能够解决应用程序布局问题。但是,你可以添加一些代码来展示如何调用render:partial?我想尝试一下。正如你在更新中看到的那样,我试过了,但是它不起作用(即使在将模板更改为_profile_messages.html.erb后)。 – tvalent2

+0

你不能链接到这样的部分。渲染:部分我的意思是这里 $(“#tabs”).html(“<%= render(:partial =>”profile_messages/profile_message“,:collection => @ profile.messages).to_json%>”) ; – mrbrdo

0

你有你的控制器定义JS的响应格式?这不该如果它能够正确呈现JS响应,就不会呈现布局。日志显示“以JS格式响应”吗?

respond_to do |format| 
    format.js 
end 

正如mrbrdo提到的那样,您也可以执行render :layout => false,但如果JS响应正常运行,则不需要。

+0

这很重要,因为他在视图内调用渲染。我不认为这个渲染会知道格式。因此,除非他将profile_messages作为该视图中的一部分呈现(他应该),否则他需要使用该布局选项。 – mrbrdo