Why do I need `render layout: false` in my Rails controller action?

前端 未结 2 1466
星月不相逢
星月不相逢 2021-01-19 17:21

I\'m use the remote: true idiom from the Working with Javascript in Rails guide:

# new.html.slim
= form_for @thing, remote: true do |f|
  f.text         


        
相关标签:
2条回答
  • 2021-01-19 17:28

    The action controller in rails responds with HTML response by default (unless otherwise instructed).

    layout 'foo' enforces the use of app/views/layouts/foo.html.slim as the template for your view files. so all the views associated with the actions on your thing_controller.rb are rendered inside the layout 'foo' and the final HTML generated with layout 'foo' and view file create.html.slim is sent back to the client by default.

    If you want to enforce returning js template instead of HTML file, you need to explicitly define it in your action like this:

    # thing_controller.rb
    layout 'foo'
    
    def create
      respond_to do |format|
        # use :template if your view file is somewhere else than rails convention
        format.js {
          :template => "somewhere/create.js.erb", 
          :layout => false
        }
      end
    end
    

    where render layout: false enforces rails NOT TO look for any layout file to wrap your view file (i.e the rails engine just processes create.js.erb file without HTML headers defined on your 'foo' layout) for sending it back to client.

    0 讨论(0)
  • 2021-01-19 17:39

    With most of the options to render, the rendered content is displayed as part of the current layout.

    You can use the :layout option to tell Rails to use a specific file as the layout for the current action:

     render layout: false
    

    You’ve heard that Rails promotes “convention over configuration.” Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to actions

    You can use it to avoid the render false for the particular action which may affect you in code latency

     layout false
     layout 'foo', :except => :create
    
    0 讨论(0)
提交回复
热议问题