【问题标题】:Provide view content in controller在控制器中提供视图内容
【发布时间】:2016-04-30 15:55:07
【问题描述】:

我有一个控制器问题,旨在检测任务/待办事项并将其传递给视图。

在我的应用程序布局中,我有一个保留空间来呈现这些任务

<%= yield(:tasks) if content_for?(:tasks) %>

这是我在 ApplicationController 中包含的模块。它似乎无法正常工作,content_for?(:tasks) 返回 false(byebug 说)

module TaskControl
  extend ActiveSupport::Concern

  included do
    before_action :check_tasks

    def check_tasks
      if user_signed_in? and current_user.tasks.todos.any?
        # TODO : better task strategy afterwards
        view_context.provide(:tasks, 
          view_context.cell(:tasks, current_user.tasks.todos.first)
        )
      end
      view_context.content_for?(:tasks) # => false :'(
    end
  end
end

请注意,我确实检查过 byebug,

view_context.cell(:tasks, current_user.tasks.todos.first).blank? # => false, so there is something to render

【问题讨论】:

    标签: ruby-on-rails mongoid actioncontroller ruby-on-rails-5 rails-cells


    【解决方案1】:

    您的控制器是否应该负责视图的工作方式?我会说不。

    使用模块/关注点来干燥查询部分而不是为产量块提供内容是有意义的。您的控制器不应该知道视图是如何构造的。

    相反,您可能希望像这样构建布局:

    <body>
      <%= yield :tasks %>
      <%= yield %>
    
      <% if @tasks %>
      <div id="tasks">
      <%= content_for(:tasks) do %>
        <%= render partial: 'tasks' %>
      <% end %>
      </div>
      <% end %>
    </body>
    

    这让控制器可以通过提供数据来设置哪些任务 - 并让您的视图通过使用 content_for or provide 来更改呈现。

    <% # app/views/foo/bar.html.erb %>
    <%= provide(:tasks) do %>
      <% # this overrides anything provided by default %>
      <ul>
         <li>Water cat</li>
         <li>Feed plants</li>
      </ul>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      相关资源
      最近更新 更多