简体   繁体   中英

How do I use a different Layout for a specific :action?

Ruby 1.8.7, Rails 2.3.11

I've been trying the answers that appear to be what I'm asking about already, but neither worked successfully for me (probably because I'm relatively new to Rails and wasn't understanding them correctly).

I'm trying to create a printer-friendly view for a model (posters), which will be accessible at /posters/print/1. How can I have the print action use a different layout file than index, new, edit, and show?

One answer said render :layout => 'otherlayout' , which I put in the print controller method to make format.xml { render :layout => 'print', :xml => @poster } . That didn't change anything when I refreshed (after clearing my cache) the page.

The other answer said

layout 'layout', :only => [:first_action, :second_action]
layout 'second_layout', :only => [:third_action, :fourth_action]

which I put at the top of the poster controller file like so:

layout 'posters', :only => [:show, :edit, :index]
layout 'print', :only => [:print]

but that appears to only use the latter line (show, edit, and index are rendered directly from their own .html.erb files, rather that wrapped inside the poster layout).

Please let me know if I need to post more information.

When you're rendering XML, it doesn't get a layout, because it's rendering XML, which doesn't use a view.

For what you're trying to do, you could simply create a printer stylesheet using stylesheet_link_tag('print', :media => :print) in your layout. This will automatically get used by the browser when you print.

There are a couple of methods you can use. One is the layouts the other is via css. Rather than having another page load and db call I would opt for the CSS method which is not hard, just change the media type to print so it looks like this:

stylesheet_link_tag 'print', :media => 'print'

For the layouts have you tried:

def print
  layout 'print'
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM