rails 3 custom mime type - default view format

2019-02-11 07:48发布

问题:

I need to render some views without layout. To skip line :render :layout=>false and if else logic from controller actions, i have custom mime type like phtml (plain html).

Mime::Type.register "text/phtml", :phtml

this format need to render the same html views, but only without layout. I complete this with this chunk of code in app. controller:

 before_filter proc { |controller|
  if params[:format] && params[:format]=='phtml'
    controller.action_has_layout = false
    controller.request.format    = 'html'

  end
  }

First, this is ugly, second i can't any more control this format from controller in the way:

respond_to :phtml,:only=>:index

because it will always render view with requested format phtml. is there a better solution? example? how can i alias view formats?

Thank a lot

回答1:

You can use the layout method in your controller directly:

class ProductsController < ApplicationController
  layout "product", :except => [:index, :rss]
end

Or to use no layout at all:

class ProductsController < ApplicationController
  layout nil
end

Check out the guide for more info.



回答2:

I haven't found better solution,only update to my previous example:

 before_filter proc { |controller|
    if params[:format] && params[:format]=='plain_html' && controller.collect_mimes_from_class_level.include?(:plain_html)
      controller.action_has_layout = false
      controller.request.format    = 'html'
    end
  }

i added this line to check is a new format defined into our controller:

controller.collect_mimes_from_class_level.include?(:plain_html)

Now we can have full new format which will render our standard html vews rather the build new views for the new format.

This can be useful if we wont to share existing html code, but build different logic based on requested format.

For example, we can easily prepare our html content for print like:

class PagesController < ActionController::Base

layout 'print',:only=>:show
respond_to :plain_html,:only=>[:show]

  def show
    Page.find(1)
    respond_with @page
  end
end

And request will be like:

http://www.example.com/pages/1.plain_html

I hope that someone will find this useful.

If u have a better approach for doing this, please share with us.

Regards