避免在Rails项目中重新加载Ruby中的布局 [英] avoiding layout reloading in ruby on rails project

查看:63
本文介绍了避免在Rails项目中重新加载Ruby中的布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ruby on rails中,我想动态加载页面数据.但是那一次我不想刷新或加载布局页面,只有主体应该渲染.我有两页,当我从一页切换到另一页时,不应重新加载布局页面数据,而应该加载另一页数据

In ruby on rails , I want to load page data dynamically. But that time i don't want to refresh or load layout page, only body should render.I am having two pages and when i switch from one page to another then the layout page data should not be reload, only another page data should load.

推荐答案

您可以在此处采用两种不同的方法.

There are two different approaches you could take here.

  1. Turbolinks-这将使更新的内容听起来比您想要的要多,但是如果您经常进行此类操作,则可能需要阅读一下. https://github.com/rails/turbolinks

使用以下方法手动使用ajax请求:

Manually using ajax requests using the following approach:

A.将以下宝石添加到您的Gemfile中 https://github.com/rails/jquery-ujs

A. Add the following gem to your Gemfile https://github.com/rails/jquery-ujs

B.将此包含在您的JS中.例如在您的JavaScript文件中,通过添加以下内容进行加载:

B. Include this in your JS. e.g. In your JavaScript file, load it by including the following:

//= require jquery
//= require jquery_ujs 

C:更新您的链接以包括远程:true:

C: Update your link to include remote: true:

<%= link_to 'New page', page_path, remote: true %>

D:在控制器中添加对js的响应.例如:

D: Add a respond to js in your controller. e.g.:

  def action_name
    respond_to do |format|
      format.html
      format.js
    end
  end

E:在视图中创建一个名为action_name.js.erb的新文件.然后,您可以在该文件中放置任何javascript代码.因此,您可以定位页面上的特定元素并将其替换为部分元素.

E: Create a new file named action_name.js.erb in your views. You can then place any javascript code within this file. So you can target a specific element on the page and replace it with a partial.

例如

$("#id_of_element_on_page").html("<%= escape_javascript(render(partial: 'page_content', locals: { project: @project })) %>");

仅此而已,当您现在单击链接时,您的应用程序应发送一个ajax请求,并应在响应中获得呈现的javascript,这反过来又应更新您希望替换的页面上的元素.

That's pretty much it, when you now click on the link, you app should send an ajax request and you should get the rendered javascript in the response which in turn should update the element on the page you wish to replace.

这篇关于避免在Rails项目中重新加载Ruby中的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆