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

前端 未结 11 1115
执念已碎
执念已碎 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 04:46

    For Rails 3, the with_format block works, but it's a little different:

      def with_format(format, &block)
        old_formats = formats
        self.formats = [format]
        block.call
        self.formats = old_formats
        nil
      end
    
    0 讨论(0)
  • 2020-11-28 04:51

    I had a file named 'api/item.rabl' and I wanted to render it from an HTML view so I had to use:

    render file: 'api/item', formats: [:json]

    (file because the file have no underscore in the name, formats and not format (and passes and array))

    0 讨论(0)
  • 2020-11-28 04:55

    Just elaborating on what zgchurch wrote:

    • taking exceptions into account
    • returning the result of the called block

    Thought it might be useful.

    def with_format(format, &block)
      old_formats = formats
      begin
        self.formats = [format]
        return block.call
      ensure
        self.formats = old_formats
      end
    end
    
    0 讨论(0)
  • 2020-11-28 04:56

    What's wrong with

    render :partial => '/foo/baz.html.erb'
    

    ? I just tried this to render an HTML ERB partial from inside an Atom builder template and it worked fine. No messing around with global variables required (yeah, I know they have "@" in front of them, but that's what they are).

    Your with_format &block approach is cool though, and has the advantage that you only specify the format, whereas the simple approach specifies the template engine (ERB/builder/etc) as well.

    0 讨论(0)
  • 2020-11-28 04:57

    Building on roninek's response, I've found the best solution to be the following:

    in /app/helpers/application.rb:

    def with_format(format, &block)
      old_format = @template_format
      @template_format = format
      result = block.call
      @template_format = old_format
      return result
    end
    

    In /app/views/foo/bar.json:

    <% with_format('html') do %>
      <%= h render(:partial => '/foo/baz') %>
    <% end %>
    

    An alternate solution would be to redefine render to accept a :format parameter.

    I couldn't get render :file to work with locals and without some path wonkiness.

    0 讨论(0)
  • 2020-11-28 04:58

    Beginning with Rails 3.2.3, when calling render :partial (only works outside of the respond_to block).

    render formats: [ :html ]
    

    instead of

    render format: 'html'
    
    0 讨论(0)
提交回复
热议问题