Benjin
Benjin

Reputation: 2409

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.

Upvotes: 0

Views: 3208

Answers (2)

Coder2000
Coder2000

Reputation: 281

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

Upvotes: 2

Tim Sullivan
Tim Sullivan

Reputation: 16888

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.

Upvotes: 1

Related Questions