干燥布局和视图

时间:2015-08-21 01:10:39

标签: ruby-on-rails ruby-on-rails-4

我有一个带侧边栏的用户个人资料页面。我需要在配置文件中创建更多页面。例如,编辑密码,编辑个人资料信息,统计信息,购买历史记录列表等。我不确定如何在保持干燥的同时继续进行。除了主要内容之外,我试图让一切都完全相同。在浏览一些教程时,我遇到了yield,但它主要用于application.html.erb来渲染导航,页脚等。我不明白如何将它用于" sub -views"

我现在这样做的方式似乎是错误的。

路线:

  as :user do
    # Routes to change password of signed in user
    get 'user/password' => 'users/registrations#edit_password', as: 'edit_password'

    # Routes to change user profile information of signed in users
    get 'user/profile' => 'users/registrations#edit_profile', as: 'user_profile'
  end

查看:

views\users\show.html.erb

views\users\registrations\edit_profile.html.erb

views\users\registrations\edit_password.html.erb

全部包含此1行

            <%= render 'users/shared/profile' %>

views\users\shared\profile

            <%= render 'users/profile/sidebar' %>

            <!-- Display Profile or Password based on route -->
            <% if current_page?(user_path current_user) %>
                <!-- User Profile -->
                <%=render 'users/profile/adminPanels' %>
            <% elsif current_page?(edit_password_path) %>
                <!-- Password Reset -->
                <%=render 'passwordForm' %>
            <% else %>
                <!-- Profile Edit -->
                <%= render 'users/registrations/profileForm' %>
            <% end %>

基本上我想要做的是保留所有周围的布局,但更改渲染的内容。现在我需要添加更多,扩展这个if语句似乎真的是错误的方法。

2 个答案:

答案 0 :(得分:0)

从您提供的代码段开始,DRYest方式就是移动 <%=render 'users/profile/adminPanels' %> 渲染show.html.erb后直接转到shared/profile页面。其他观点也是如此。

答案 1 :(得分:0)

是的,这绝对不是一种可行的方式,但是你认识到这一点并不令人担忧,这很好。正如您猜测的那样,执行此操作的方法涉及使用布局和yield。您可以在this Rails guide中了解收益率。

虽然您可以使用默认情况下整个Rails应用程序使用的application.rb等布局,但您也可以定义嵌套在此布局中的布局。这与上面的towards the bottom相同的Rails指南中描述。

这样,整个应用程序的相同内容在application布局中定义,对于用户配置文件的所有内容都相同的内容在users布局中定义,并且在那里定义了特定于每个视图的东西。

旁注:,因为users文件夹位于layouts文件夹中,我的行为就好像你移动了_sidebar部分一样,因为它是真的是属于布局的部分,应该靠近它。

<强>视图/布局/ users.html.erb

<%= render '_sidebar' %>
<%= yield :users_content %>
<%= render template: 'layouts/application' %>

<强>视图/用户/ show.html.erb

<% content_for :users_content do %>
  put the view code specific to users/show here
<% end %>

<强>视图/用户/注册/ edit.html.erb

<% content_for :users_content do %>
  put the view code specific to editing a user registration here
<% end %>

你唯一可能遇到的问题是Rails使用控制器的名称来匹配嵌套的users布局,如果那个&#39; sa可能会破坏registrations的内容不同控制器。您可以通过在这些控制器操作中显式调用render template: 'layouts/users'来解决此问题。

相关问题