I have a Rails controller which provides both HTML and PDF responses, and thus I have view.pdf.haml and view.html.haml files. These are either identical or extremely close to identical.
How can I have Rails use a single view for multiple formats?
CodePudding user response:
One option is to have your view.html.haml file simply render the view.pdf.haml file as a partial, or vice versa. This does use two views, but one view will just be a single line, pointing to the other.
However, here is one way to point both formats to the same view in your controller:
respond_to do |format|
format.html { render(file: '<replace with relative/absolute path to view>') }
format.pdf { render(file: '<replace with relative/absolute path to view>') }
end
CodePudding user response:
Do you mean have the same action serve up different resource types - i.e. both a web page and a PDF? If I understand the problem, you can use the respond_to method.
def show
@object = Object.find params[:id]
respond_to do |format|
format.html
format.pdf { ..code to render the pdf.. }
end
end
That ..code to render the pdf.. is the tricky part. There are PDF gems that support inline rendering, but you may end up using send_data or similar to set a file name, disposition, etc and deliver the PDF document to the end user.
