简体   繁体   English

如何从控制器的每个动作渲染一个通用的 JS?

[英]How to render a common JS from every action of controller?

For example, I have a controller named Organizations , which includes basic CRUD actions and all the actions respond_to JS, so I wrote the respond_to block at the beginning of the controller respond_to :js, { only: %i[index destroy create] } and now want to render a common JS for all these actions ie want to render index.js.erb on all actions rather than all action specific JS.例如,我有一个名为Organizations控制器,它包括基本的 CRUD 动作和所有动作respond_to JS,所以我在控制器respond_to :js, { only: %i[index destroy create] }的开头写了respond_to块现在想要为所有这些动作呈现一个公共 JS,即想要在所有动作上呈现index.js.erb ,而不是所有特定于动作的 JS。 So What can be the solution for the same?那么相同的解决方案是什么?

You can override the implicit rendering by overriding the default_render method provided by ActionController::ImplicitRender .您可以通过覆盖ActionController::ImplicitRender提供的default_render方法来覆盖隐式渲染。

class OrganizationsController < ApplicationController
  def default_render(*args)
    # is there an action specific template?
    if template_exists?(action_name.to_s, _prefixes, variants: request.variant)
      super
    # is there an index template we can use insted?
    elsif template_exists?('index', _prefixes, variants: request.variant) 
      render :index, *args
    # We don't have a template. lets just let the default renderer handle the errors
    else 
      super
    end
  end
  # ...
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从控制器动作中呈现部分内容(没有JS ERB,只有用户呈现js:“ command_string”) - How to render partial from controller action (no JS ERB, just user render js: “command_string”) 如何在Rails 4.2中的动作中呈现不同的控制器/动作? - How to render a different controller / action from within an action in Rails 4.2? Rails-在控制器中,如何从其他控制器渲染动作? - Rails - in controller, how to render an action from a different controller? Rails:如何选择要呈现控制器动作的js文件? - Rails: How to choose which js file a controller action to render? Rails:如何在控制器中呈现其他动作,在js中不在html中? - Rails : how to render an other action in the controller, in js not in html? 工作如何在控制器中呈现动作? - How work render action in controller? 从另一个控制器渲染控制器操作 - Render controller action from another controller Rails 3:如何从另一个控制器的视图呈现动作 - Rails 3: How to render an action from another controller's view 如何从同一控制器内的另一个动作呈现动作并传递参数 - How to render action from another action inside same controller and pass parameters 如何确定在控制器操作中呈现哪个视图 - How to determine which view to render in a controller action
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM