如何在我的 application.html.erb View 中显示 Rails 中不同版本的 header ?例如,对于我的登陆页面,我有一个相当大的标题,其中包括标注以及一些注册和登录按钮。对于其他静态页面,我有一个带有 Logo 的普通小标题和右侧的一些链接。对于我的仪表板,当用户登录时,它看起来也会有点不同。
如何在 if/else 语句中显示某些 header ,其中 Rails 将根据当前 url 或 application.html.erb 中的 View 输出不同版本的 header ?
最佳答案
您可能想要用一个例子来回答您的问题。
Rails 提供了使用 content_for
来使用嵌套 View 模板的规定。和yield
标签。
做以下事情来实现你想要的 -
在
app/views/layouts/application.html.erb
- 添加一个三元表达式,充当if else
。渲染 View 时,rails 将查找<% content_for :custom_header do %>
在 View 模板中。如果没有找到,它将渲染部分app/views/layouts/_default_header.html.erb
相反。<html> <head> <title><%= @page_title or "Page Title" %></title> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %> </head> <body> <!-- Code to conditionally load a header --> <%= content_for?(:custom_header) ? yield(:custom_header) : render :partial => "layouts/default_header" %></div> <!-- For the body --> <%= yield %> </body> </html>
既然你说大多数页面都会有一个静态的小标题,请将其 html 代码保存在
app/views/layouts/_default_header.html.erb
下的部分中。 .在您的登陆页面(例如 View
app/views/welcome/index.html.erb
)中,您可以使用content_for
带有标识符:custom_header
的标签我们在application.html.erb
中使用过 在您的目标网页中添加以下内容。<% content_for :custom_header do %> <div class="custom-header"> <!-- Your complex header with sign in and signup links... --> </div> <% end %>
application.html.erb
中的三元运算符将从登陆页面的 content_for 标记中获取此内容,并将该内容插入到 yield(:custom_header)
的位置。 .
希望这有帮助。
关于ruby-on-rails - 如何在 Rails 的 application.html.erb 中显示不同的 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964713/