我正在编写一个 Rails 应用程序。我想在索引页的整个 HTML 标记中使用特定的样式,但其余页面应遵循应用程序布局。所以,在我的控制器中我有:
def index
render layout: 'index_layout'
end
# All other actions follow this scheme
def any_other_action
end
索引布局有一段特定的代码可以更改样式:
<!-- Index layout -->
<html id="index_html">
...
<!-- Application layout (goes normally) -->
<html>
...
但是,当我通过 Rails 中的
link_to
标签从一个窗口更改为另一个窗口时,布局不会刷新,视图仍保留上一页中分配的 id,例如,如果我从索引转到任何其他页面,html标签的id为index_html,反之亦然。但是,如果我执行完全刷新(按 F5 键),布局将正确呈现。我在 Mozilla Firefox 和 Chrome 中进行了测试,以检查这是否是浏览器特有的问题,但结果是相同的。
当我请求索引页面时,在通过
link_to
标签导航到任何其他页面,然后重新加载此新页面后,我的服务器会生成此输出:
Processing by HomeController#index as HTML
Rendering home/index.html.haml within layouts/index_layout
Rendered home/index.html.haml within layouts/index_layout (9.9ms)
Rendered layouts/_navbar.html.haml (13.6ms)
Completed 200 OK in 1254ms (Views: 1201.9ms | ActiveRecord: 0.0ms)
# Navigation with link_to tag, the index_html id is still appearing
Started GET "/community" for 127.0.0.1 at 2018-06-09 11:45:58-0500
Processing by HomeController#community as HTML
Rendering home/community.html.haml within layouts/application
Rendered home/_community_members_panel.html.haml (6.1ms)
Rendered home/_community_companies_panel.html.haml (8.1ms)
Rendered home/community.html.haml within layouts/application (41.5ms)
Rendered layouts/_navbar.html.haml (10.6ms)
Completed 200 OK in 110ms (Views: 101.0ms | ActiveRecord: 0.0ms)
# Full refresh of the page with F5 key, the index_html id doesn't appear, as it should.
Started GET "/community" for 127.0.0.1 at 2018-06-09 11:46:49 -0500
Processing by HomeController#community as HTML
Rendering home/community.html.haml within layouts/application
Rendered home/_community_members_panel.html.haml (5.6ms)
Rendered home/_community_companies_panel.html.haml (6.6ms)
Rendered home/community.html.haml within layouts/application (19.4ms)
Rendered layouts/_navbar.html.haml (8.4ms)
Completed 200 OK in 74ms (Views: 72.7ms | ActiveRecord: 0.0ms)
任何人都可以告诉我一些可能出现故障的情况吗?我的直觉是关于缓存的,但我找不到任何可以帮助我的答案。我的 Ruby 版本是 2.5.1,我的 Rails 版本是 5.1.6
我认为获得 Ur 客户布局的最简单方法是创建一个布局,其中控制器的名称作为文件夹名称,index.html.erb 来反映 Ur 的操作。
1)
before_action custom_layout, only: :index
def custom_layout
render 'layouts/index_layout'
end
2)
layout :layout_by_resource
def layout_by_resource
if true #just check as you want here. controller/path/actions etc...
"index_layout"
else
"application"
end
end
我发布此内容希望这对遇到我提出的问题的任何人都有帮助
问题是
turbolinks
宝石。看起来,当您使用此 gem 创建链接时,它只会重新加载页面的正文。因此,当通过链接重定向时,html 标记不会更改,但在刷新时会更改。我所要做的就是在链接标签中添加下一个代码:
<%= link_to about_us_path, data: {turbolinks: false} %>
因此,布局被完全重绘,应用所需的更改。
感谢大家的回答!
我也遇到了同样的问题,这就是我解决的方法:
<%= link_to about_us_path, data: {turbo: false} %>
使用 Rails 7.1