ChatGPT解决这个技术问题 Extra ChatGPT

Turn off layout for one of action

My situation: View action of ReportsController should render pure html, but not as a file (to view it in browser and save it after). So for rendering I use view template view.html.erb and i neet to turn off any layouts for this action. But in other actions of this controller layouts should stay untouched. Works only turning off for whole controller like this:

ReportsController < ApplicationController
  layout false

But that doing it wrong :( for all the actions I tried to use something like this in action:

def view      
  @report = Report.new(params[:report])
  unless @report.valid?
    render :action => 'new' and return
  else
    render :layout => false     
  end   
end

What should I do?

Well, you definitely don't need that explicit return. Do you want the layout to render if the report is valid?

D
David Ortiz

This should do it,

def view
    ...
    render :layout => false
end

Link to Documentation


The problem with this is you'd have to specify layout: false for every format in the action.
life is beautiful when there are answers! :-D
T
Tadas Sasnauskas

Try this:

ReportsController < ApplicationController
  layout false
  layout 'application', :except => :view

It seems like this directive works wrong (or unexpected). I tried to use some combinations of these parameters (:only, :except). But it worked strange removing all the layouts for all the actions. I think it's because of nil or false instead of 'layoutname'. And system tries to use 'controllername' layouts for all the other actions ignoring application layout. Try to play with this parameters and you'll understand what this all about.
You're right, :only doesn't work properly on layout nil. I was able to get it working by nilling the layout and adding it back with the exception, however. I've updated my answer.
Answer by David Ortiz is "more correct," as it properly isolates the layout switch to the lone action in question.
I agree with @Paul - false works! Thanks for that!
layout false, only: :view feels like a more concise way to accomplish the same goal without side effects like Antiarchitect mentions.
A
Archonic

In the respond block, add layout: false.

For example:

respond_to do |format|
  format.html { render :layout => false }
end

M
Mugur 'Bud' Chirica

If you want to get a non-standard template, with no layout you can use:

def non_rest
  render template: 'layouts/something_new', layout: false
end

How about the opposite - can I render the default layout with no template?

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now