ruby-on-rails - 如何在 Rails 的 application.html.erb 中显示不同的 header ?

标签 ruby-on-rails ruby view

如何在我的 application.html.erb View 中显示 Rails 中不同版本的 header ?例如,对于我的登陆页面,我有一个相当大的标题,其中包括标注以及一些注册和登录按钮。对于其他静态页面,我有一个带有 Logo 的普通小标题和右侧的一些链接。对于我的仪表板,当用户登录时,它看起来也会有点不同。

如何在 if/else 语句中显示某些 header ,其中 Rails 将根据当前 url 或 application.html.erb 中的 View 输出不同版本的 header ?

最佳答案

您可能想要用一个例子来回答您的问题。 Rails 提供了使用 content_for 来使用嵌套 View 模板的规定。和yield标签。 做以下事情来实现你想要的 -

  1. 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>
    
  2. 既然你说大多数页面都会有一个静态的小标题,请将其 html 代码保存在 app/views/layouts/_default_header.html.erb 下的部分中。 .

  3. 在您的登陆页面(例如 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/

相关文章:

javascript - 之前的web form录入数据后,如何让web form出现?

ruby-on-rails - 为什么我的 View 出现语法错误?

ruby-on-rails - 错误 : Exhausted all sources trying to fetch version 'latest' of RVM

ruby - 使用 cedet 语义 wisent-ruby

android ProgressDialog : setting custom view instead of message - does this work?

c# - 登录前隐藏菜单,登录后显示

iOS View 可见性消失

ruby-on-rails - 部署到Heroku时出现ActionView错误,在本地可以正常运行

ruby-on-rails - Rails 4 Assets 管道链接

ruby-on-rails - 从表中删除与数组中的数据匹配的记录?