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

前端 未结 11 1116
执念已碎
执念已碎 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:03

    In Rails 3, the View has a formats array, which means you can set it to look for [:mobile, :html]. Setting that will default to looking for :mobile templates, but fall back to :html templates. The effects of setting this will cascade down into inner partials.

    The best, but still flawed way, that I could find to set this was to put this line at the top of each full mobile template (but not partials).

    <% self.formats = [:mobile, :html] %>
    

    The flaw is that you have to add that line to multiple templates. If anyone knows a way to set this once, from application_controller.rb, I'd love to know it. Unfortunately, it doesn't work to add that line to your mobile layout, because the templates are rendered before the layout.

    0 讨论(0)
  • 2020-11-28 05:03

    You have two options:

    1) use render :file

    render :file => "foo/_baz.json.erb"
    

    2) change template format to html by setting @template_format variable

    <% @template_format = "html" %>
    <%= h render(:partial => '/foo/baz') %>
    
    0 讨论(0)
  • 2020-11-28 05:08

    It seems that passing a formats option will render it properly in newer Rails version, at least 3.2:

    {
      someKey: 'some value',
      someHTML: "<%= h render('baz', formats: :html) -%>"
    }
    
    0 讨论(0)
  • 2020-11-28 05:09

    I came across this thread when I was trying to render an XML partial in another xml.builder view file. Following is a nice way to do it

    xml.items :type => "array" do
        @items.each do |item|
            xml << render(:partial => 'shared/partial.xml.builder', :locals => { :item => item })
        end
    end
    

    And yeah... Full file name works here as well...

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题