How do I render a partial of a different format in Rails?

前端 未结 11 1252
执念已碎
执念已碎 2020-11-28 04:21

I\'m trying to generate a JSON response that includes some HTML. Thus, I have /app/views/foo/bar.json.erb:

{
  someKey: \'some value\',
  someH         


        
11条回答
  •  半阙折子戏
    2020-11-28 05:10

    Rails 4 will allow you to pass a formats parameter. So you can do

    render(:partial => 'form', :formats => [:html])} 
    

    Note you can do something similar in Rails 3 but it wouldn't pass that format to any sub partials (if form calls other partials).

    You can have the Rails 4 ability in Rails 3 by creating config/initializers/renderer.rb:

    class ActionView::PartialRenderer
      private
      def setup_with_formats(context, options, block)
        formats = Array(options[:formats])
        @lookup_context.formats = formats | @lookup_context.formats
        setup_without_formats(context, options, block)
      end
    
      alias_method_chain :setup, :formats
    end
    

    See http://railsguides.net/2012/08/29/rails3-does-not-render-partial-for-specific-format/

提交回复
热议问题